算法总结(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
- 算法总结(2)--买股票最大盈利问题
- Leetcode 求买股票的最大盈利问题
- java 动态规划判断股票最大盈利问题
- 买股票最大利润
- 买股票
- 计算股票最佳盈利
- 买卖股票收益最大问题
- 第四章 最大子数组问题(股票最大收益) C++实现 算法导论
- 算法导论之求股票最大收益
- 贪心算法 Problem N 1013 求最大盈利
- 试题:基本算法题之【计算买股票的第n天每股股票值多少钱】
- 股票中买1、买2、买3和卖1、卖2、卖3
- 今年买股票不错
- 程序员如何买股票
- 我要买股票
- 第一次出马买股票
- 第二次出手买股票
- 第三次出手买股票
- 面试题总结(二)
- Cordova 搭建IOS开发环境-console日志调试
- Jdbc入门介绍第二章——Jdbc结合JSP和Servlet的简单综合应用
- Spring源码解析---spring源码下载导入eclipse
- Using version 1.0.0-alpha8 of the constraint library, which is obsolete
- 算法总结(2)--买股票最大盈利问题
- How Does Cloudera Manager Work
- android初级学习之Handler详解
- Android _实现SSL解决不受信任的证书问题
- Spring4 Profile
- Android-Universal-Image-Loader 图片异步加载类库的使用(超详细配置)
- 机器学习03-贝叶斯算法
- Python3.5安装Matplotlib
- 轮播图案例