Best Time to Buy and Sell Stock II
来源:互联网 发布:新西兰留学 知乎 编辑:程序博客网 时间:2024/06/05 10:43
一开始考虑的动态规划的想法,dp[i]=max(dp[j]+a[i]-a[j]),结果超时。其实这是没有必要的,因为如果abc三个数,当a<c时,如果b>c的时候,只需要考虑ab;如果a<b<c时,分别计算a<b和b<c,不会出现跳跃的情况。
class Solution {public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size()==0) return 0; vector<int> dp; for(int i=0;i<prices.size();i++) dp.push_back(0); for(int i=0;i<prices.size();i++) for(int j=0;j<=i;j++){ if(dp[i]<dp[j]+prices[i]-prices[j]) dp[i]=dp[j]+prices[i]-prices[j]; } return dp[prices[prices.size()-1]]; }};
class Solution {public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size()==0) return 0; int res=0; for(int i=1;i<prices.size();i++) res+=prices[i]-prices[i-1]>0?prices[i]-prices[i-1]:0; return res; }};
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- navicat for mysql ubuntu快捷方式
- linux下的环境变量
- 将物理机正使用的操作系统制作成LiveCD笔记[未测试]
- 几个重要库函数的实现-strcpy,strncpy,memcpy,memset
- HDU 4766 Network(计算几何 二分+三分)
- Best Time to Buy and Sell Stock II
- 2014阿里巴巴笔试题
- poj 1451 T9 字典树
- svn常用命令
- [MAC]SFML 2.x + Mac OS X 小结
- win7与ubuntu12.10双系统下硬盘安装centos5.3
- Thinkpad在Ubuntu下禁用触摸板但不禁用小红帽
- java Label
- 《程序员面试宝典》第3版大量错误纠正表