(LeetCode)Best Time to Buy and Sell Stock II
来源:互联网 发布:微信分享链接怎么弄 js 编辑:程序博客网 时间:2024/06/05 14:22
求在已知一支股票价格变化的情况下能取得的最大收益。
class Solution {public: int maxProfit(vector<int> &prices) { int *v=new int [prices.size()]; int ans=0; for (int i=0;i<prices.size();i++){ int tmp=(!(i==0)?prices[i]-prices[i-1]:0); v[i]=tmp; } for (int i=1;i<prices.size();i++){ if(v[i-1]>=0&&v[i]>=0) v[i]+=v[i-1]; } int tmp=-0xfffffff; for(int i=0;i<prices.size();i++){ // cout<<v[i]<<"++++"<<endl; if(v[i]<0)ans+=(tmp>0?tmp:0),tmp=-0xfffffff; if(v[i]>tmp)tmp=v[i]; } ans+=(tmp>0?tmp:0); if (prices.size()==0) { ans=0; } return ans; } };
其实只要在上升段把每个点的差的和相加就可以。
for(i=1;i<len;++i) { if(prices[i]>prices[i-1]) { result += prices[i]-prices[i-1]; } }
0 0
- [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
- 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
- 【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
- [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
- [leetcode] Best Time to Buy and Sell Stock II
- 代码审查和不良编程习惯
- Oracle用户Profile详解
- SVN使用过程中出现的错误记录(一)
- 林丹 - 没有人想永远输给你
- SSO (单点登录)实现方式
- (LeetCode)Best Time to Buy and Sell Stock II
- 013 Java 多态和内部类
- va_start和va_end使用详解
- Android重写View
- 蹭的WiFi的信号还能增强?
- 深入浅出-iOS程序性能优化
- VC串口编程基础-各种数据校验方法
- 每个Java开发者都应该知道的5个JDK工具
- 用递归求n的阶乘