算法总结(2)--买股票最大盈利问题

来源:互联网 发布:淘宝的cf号哪来的 编辑:程序博客网 时间:2024/06/11 15:59

stock 买,卖交易,最大收入问题

动态规划,双指针法等,主要是动态规的几个要点

309 . Best Time to Buy and Sell Stock with Cooldown 这题采用了状态转换的动归做法,比较难?

==

121. Best Time to Buy and Sell Stock

题目地址

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

一次交易

123. Best Time to Buy and Sell Stock III

题目地址

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

#

最多两次交易

122. Best Time to Buy and Sell Stock II

题目地址

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

#

不限交易次数

188. Best Time to Buy and Sell Stock IV

题目地址

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

限制最大的交易次数

采用动态规划来做,ac代码如下
主要是位置一个交易的持有和卖出变量,动归求解

class Solution {public:    int maxProfit(int k, vector<int>& prices) {        int len = prices.size();        if (len <= 1 || k <= 0)            return 0;        if (k > len / 2) // 不限制次数        {            int result = 0;            for (int i = 1; i < len; ++i) {                if (prices[i] - prices[i - 1] > 0) {                    result += prices[i] - prices[i - 1];                }            }            return result;        }        int INF = 0x7fffffff;        int MIN = -1 - INF;        vector<int> hold(k + 1, MIN); // 第k次交易持有的亏损        vector<int> sell(k + 1,0); // 第k次交易卖出后的盈利情况        int cur;        for (int i = 0; i < len; i++)        {            cur = prices[i];            for (int j = 1; j <= k; j++)            {                sell[j] = max(sell[j], hold[j] + cur); // 当前卖出 + 上一次的买入                hold[j] = max(hold[j], sell[j - 1] - cur); // 当前买入  + 上一次的卖出            }        }        return sell[k];    }};

309. Best Time to Buy and Sell Stock with Cooldown

题目地址

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

添加一个限制条件

思路参考
http://www.cnblogs.com/jdneo/p/5228004.html

类似题

238. Product of Array Except Self

题目地址

https://leetcode.com/problems/product-of-array-except-self/

类似两点法

ac代码

class Solution {public:    vector<int> productExceptSelf(vector<int>& nums) {        vector<int> ans;        int len = nums.size();        vector<int> left(len); // 除i之外的左边乘积        vector<int> right(len); // 除i之外的右边乘积        left[0] = 1;        left[1] = nums[0];        for (int i = 2; i < len; i++){            left[i] = left[i - 1] * nums[i - 1];        }        right[len - 1] = 1;        right[len - 2] = nums[len - 1];        for (int i = len - 3; i >= 0; i--){            right[i] = nums[i + 1] * right[i + 1];        }        for (int i = 0; i < len; i++){            int vi = left[i] * right[i];            ans.push_back(vi);        }        return ans;    }};
0 0