`
cozilla
  • 浏览: 89432 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[LeetCode]Best Time to Buy and Sell Stock 1 2 3

 
阅读更多

1.

 

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

复杂度:O(N)

 

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if (prices.size() < 2) return 0;
        int curres = 0;
        int curmin = prices[0];
        for (int i = 1; i < prices.size(); i++) {
            if (curres < prices[i] - curmin)
                curres = prices[i] - curmin;
            curmin = (curmin > prices[i] ? prices[i] : curmin);
        }
        return curres;
    }
};

 

 

 

 

2.

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

注意: you must sell the stock before you buy again. 就是说只能有一个stock在手中。否则的话,问题会很复杂。

之前没有注意这个条件。想错了。

方法:寻找连续递增区间。

复杂度:O(N)

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if (prices.size() < 2) return 0;
        int res = 0;
        int start = prices[0];
        for (int i = 1; i < prices.size(); i++) {
            if (prices[i] >= prices[i-1]) continue;
            
            res += prices[i-1] - start;
            start = prices[i];
        }
        res += *(prices.end()-1) - start;
        return res;
    }
};

 

 

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n = prices.size();
        if (n == 0) return 0;
        int res = 0;
        auto &a = prices;
        int s = 0, e;
        while (s < n) {
            e = s + 1;
            while (e < n && a[e] >= a[e-1]) e++;
            res += a[e-1] - a[s];
            s = e;
        }
        return res;
    }
};

 

3.

 

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

注意:第三问还是需要注意  you must sell the stock before you buy again
因为只能持有1stock。所以两次transactions一定是相互分开的。例如:1 2 5 3 6。答案应该是7 = (1,5) (3,6);而不是8 = (1,5) (2,6);
方法:把prices[1~n]分成prices[1~i]和prices[i+1~n]两段,然后在两段内各做一次transaction。如果能用O(1)的方式在prices[1~i] and prices[i+1~n]内找到最大profit。就ok了。
参考问题1中的方法。可以O(N)扫一遍:记录下在第i天之前做一次交易的最大值。则可以解决在prices[1~i]的找最大值的问题。而i+1~n其实就是把从n开始扫一边数组,记录下 i+1~n之间的最大值。

 

复杂度:O(N)

 

#define min(a,b) ((a) > (b) ? (b) : (a))
#define max(a,b) ((a) < (b) ? (b) : (a))

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if (prices.size() < 2) return 0;
        int s = prices.size();
        int *a = new int[s+1];
        int *b = new int[s+1];
        memset(a, 0, 4*s+4);
        memset(b, 0, 4*s+4);
        
        int curm = prices[0];
        a[0] = 0;
        for (int i = 1; i < s; ++i) {
            a[i] = max(a[i-1], prices[i] - curm);
            curm = min(curm, prices[i]);
        }
        
        curm = prices[s-1];
        b[s-1] = 0;
        for (int i = s-2; i >=0; --i) {
            b[i] = max(b[i+1], curm - prices[i]);
            curm = max(curm, prices[i]);
        }
        
        int res = 0;
        for (int i = 0; i < s; i++) {
            res = max(res, a[i] + b[i+1]);
        }
        
        delete []a;
        delete []b;
        return res;
    }
};

 

 

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n = prices.size();
        if (n == 0) return 0;
        vector<int> r1(n,0);
        vector<int> r2(n,0);
        auto &a = prices;
        
        int m = a[0];
        for (int i = 1; i < n; i++) {
            r1[i] = max(r1[i-1], a[i] - m);
            m = min(a[i], m);
        }
        m = a[n-1];
        for (int i = n - 2; i >= 0; i--) {
            r2[i] = max(r2[i+1], m - a[i]);
            m = max(a[i], m);
        }
        int res = r2[0];
        for (int i = 0; i < n - 1; i++) {
            res = max(res, r1[i] + r2[i+1]);
        }
        res = max(res, r1[n-1]);
        
        return res;
    }
};

 

 

分享到:
评论

相关推荐

    leetcode题目:Best Time to Buy and Sell Stock II

    leetcode题目:Best Time to Buy and Sell Stock II

    lrucacheleetcode-LeetCode:CppSourceCode的LeetCode解决方案

    leetcode LeetCode 解决题目的总数: 136/1753 微信公众号: 工程师Ruojhen 算法-动态规划 题号 名称 English Name 题解 53 最大子序和 Maximum Subarray 70 爬楼梯 Climbing Stairs 121 买卖股票的最佳时机 Best Time...

    javalruleetcode-leetcode-java:力码笔记

    1.Two Sum 3.Longest Substring Without Repeating Characters 5.Longest Palindromic Substring 20.Valid Parentheses 26.Remove Duplicates from Sorted Array 53.Maximum Subarray 70.Climbing Stairs 121.Best ...

    股票收益leetcode-leetcode:leetcode摘要

    股票收益leetcode LeetCode 股票问题 Best Time to Buy and Sell Stock (Easy) 一次交易,找最大收益 for i in prices: low = min(low, i) profit = max(profit, i-low) Best Time to Buy and Sell Stock II (Easy) ...

    leetcode分类-LeetCode:力码

    很多代码并不简洁,本来1行的代码可以写成3行 思维混乱 没有按照题目类型分类 没有写结题思路 最近花时间分门别类整理了 LeetCode 的前 500 题,把相似的题目都放在了一起,比如Best Time to Buy and Sell Stock的6...

    LeetCode:LeetCode Java解决方案

    公众号 coding 笔记、点滴记录,以后的文章也会...最近花时间分门别类整理了 LeetCode 的前 500 题,把相似的题目都放在了一起,比如Best Time to Buy and Sell Stock的6道题,这些题目放在一起刷效果更好。 简书博客:

    Andy619-Zhu#CS-Notes-chu#63. 股票的最大利润1

    63. 股票的最大利润题目链接Leetcode:121. Best Time to Buy and Sell Stock题目描述可以有一次买入和一次卖出,买入必

    LeetCode最全代码

    15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || Two Pointers 16 | [3 Sum Closest]...

    Leetcode的ac是什么意思-LeetCodeInJava:leetcode-java

    Leetcode的ac是什么意思 LeetCodeInJava List #98 Validate Binary Search Tree #100 Same Tree #104 Maximum Depth of Binary Tree #122 Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate ...

    cpp-算法精粹

    Best Time to Buy and Sell Stock with Cooldown Interleaving String Scramble String Minimum Path Sum Edit Distance Decode Ways Distinct Subsequences Word Break Word Break II Dungeon Game House Robber ...

    股票买卖最佳时机leetcode-best-time-to-buy-and-sell-stock:让我们弄清楚什么时候买一些股票!这不应该在现

    股票买卖最佳时机leetcode GitFitCode 配对编码挑战! 买卖股票的最佳时机 让我们弄清楚什么时候买一些股票! 这不应该在现实生活中使用。 现在不管你认为你的算法有多好:)。 我确实鼓励您选择一只您感兴趣的股票,...

    LeetCode:Leetcode-解决方案

    Best Time to Buy and Sell Stock [121]3. Climbing Stairs [70]4. Maximum Subarray [53]5. House Robber [198]6. Range Sum Query - Immutable [303]7. Counting Bits [338]8. Palindromic Substrings [647]9. ...

    leetcode-leetcode:leetcode的最佳C++解决方案

    leetcode leetcode The optimum C++ solutions for the leetcode 这是我自己写的leetcode的题解,目前已经完成了70%左右,后续部分会很快更新 这里放上来的代码都能保证是最优解(复杂度最优) 当然有些题目因为测试...

    leetcode小岛出水口-leetcode:leetcode训练

    leetcode小岛出水口 leetcode training one problem on file 为了方便文档管理,项目逐渐文档化,以单个文件作为集合最小集。 go语言不能完全适合写算法题 后续会尽可能加入rust或者c的题解 清单 0965. Univalued ...

    leetcode卡-leetcode:利特码解决方案

    leetcode卡 leetcode exercises 3-5 solutions everyday. fighting~ TODO array Best Time to Buy and Sell Stock II Valid Sudoku linked list Palindrome linked list Linked List Cycle trees Convert Sorted ...

    lrucacheleetcode-LeetCode_30Day:力扣30天挑战赛

    lru缓存leetcode 力扣_30天 力扣 30 天挑战赛 日 问题描述 问题和解决方案链接 Git 解决方案页面 1 SINGLE NUMBER 2 HAPPY NUMBER 3 MAXIMUM SUBARRAY 4 Move Zeroes 5 Best Time to Buy and Sell Stock II 6 GROUP ...

    leetcode中文版-leetcode:leetcode

    leetcode中文版车鸟 一组用python编写的算法。 种类 ...best_time_to_buy_and_sell_stock_II binary_tree_inorder_traversal binary_tree_level_order_traversal binary_tree_level_order_traversal_I

    leetcode浇花-LCSolutions:我的力扣解决方案

    leetcode 浇花力扣解决方案 简单的 #0001 - Two Sum #0007 - Reverse Integer #0009 - Palindrome Number #0035 - Search Insert Position #0058 - Length of Last Word #0066 - Plus One #0083 - Remove Duplicates...

    LeetCode:LeetCode题解

    Best_Time_To_Buy_And_Sell_Stock Java 简单的 122 Best_Time_To_Buy_And_Sell_StockII Java 简单的 125 Valid_Palindrome Java 简单的 136 单号 Java 简单的 137 Single_NumberII Java 中等的 167 Two_...

    gasstationleetcode-LeetCode_Practice:我的LeetCode练习从2020年开始

    加油站 leetcode 力扣_实践 标签: leetcode 我的 LeetCode 练习从 2020 年开始 前言 ...Leetcode ...299_Bulls_and_Cows ...121_Best_Time_to_Buy_and_Sell_Stock 122_Best_Time_to_Buy_and_Sell_Stock_

Global site tag (gtag.js) - Google Analytics