Best Time to Buy and Sell Stock III
来源:互联网 发布:阿里云新用户邀请码 编辑:程序博客网 时间:2024/05/15 23:01
class Solution {
public:
///设状态 f ( i ),表示区间 [0 , i ](0 ≤ i ≤ n − 1) 的最大利润,从前向后遍历(表示i之前的数组的最大利润),用最大的-最小的
//状态 g ( i ),表示区间 [ i, n − 1](0 ≤ i ≤ n − 1) 的最大利润,从后向前遍历(表示i之后的数组的最大利润),也用最大的-最小的
//则最终答案为 max {f (i ) + g (i )} , 0 ≤ i ≤ n − 1。
//允许在一天内买进又卖出,相当于不交易,因为题目的规定是最多两次,而不是一定要两次。
//将 原 数 组 变 成 差 分 数 组, 本 题 也 可 以 看 做 是 最 大 m 子 段 和, m = 2
int maxProfit(vector<int> &prices)
{
if(prices.size()<=1) return 0;
int len=prices.size();
vector<int>ivec(len,0);
vector<int>ivec1(len,0);
int min1=prices[0],max1=0;
int result=0;
for(int i=1;i<len;i++)
{
max1=max(prices[i]-min1,max1); //从前往后,找出前面的最小值,然后存最大收益;
ivec[i]=max1;
min1=min(prices[i],min1);
}
int maxval=prices[len-1];
max1=0;
for(int i=len-2;i>=0;i--) //从后往前再遍历一次,不过效果不同; 找出最大值,然后存最大收益
{
max1=max(maxval-prices[i],max1);
ivec1[i]=max1;
maxval=max(prices[i],maxval);
}
for(int i=0;i<len;i++)
result=max(ivec[i]+ivec1[i],result);
return result;
}
};
public:
///设状态 f ( i ),表示区间 [0 , i ](0 ≤ i ≤ n − 1) 的最大利润,从前向后遍历(表示i之前的数组的最大利润),用最大的-最小的
//状态 g ( i ),表示区间 [ i, n − 1](0 ≤ i ≤ n − 1) 的最大利润,从后向前遍历(表示i之后的数组的最大利润),也用最大的-最小的
//则最终答案为 max {f (i ) + g (i )} , 0 ≤ i ≤ n − 1。
//允许在一天内买进又卖出,相当于不交易,因为题目的规定是最多两次,而不是一定要两次。
//将 原 数 组 变 成 差 分 数 组, 本 题 也 可 以 看 做 是 最 大 m 子 段 和, m = 2
int maxProfit(vector<int> &prices)
{
if(prices.size()<=1) return 0;
int len=prices.size();
vector<int>ivec(len,0);
vector<int>ivec1(len,0);
int min1=prices[0],max1=0;
int result=0;
for(int i=1;i<len;i++)
{
max1=max(prices[i]-min1,max1); //从前往后,找出前面的最小值,然后存最大收益;
ivec[i]=max1;
min1=min(prices[i],min1);
}
int maxval=prices[len-1];
max1=0;
for(int i=len-2;i>=0;i--) //从后往前再遍历一次,不过效果不同; 找出最大值,然后存最大收益
{
max1=max(maxval-prices[i],max1);
ivec1[i]=max1;
maxval=max(prices[i],maxval);
}
for(int i=0;i<len;i++)
result=max(ivec[i]+ivec1[i],result);
return result;
}
};
0 0
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- 集群搭建时候遇到的一个问题
- 事件默认行为
- NYOJ324 猴子吃桃问题
- Hibernate 与mybatis的区别
- Mongodb Sharding 术语
- Best Time to Buy and Sell Stock III
- C++ HOJ N皇后问题
- java判断list为空的方法
- 从指定网站下载文件
- 黑马程序员-Foundation框架之NSDirctionary类以及NSMutableDirctionary类
- <大数据日知录 架构与算法>读后
- 学习日记1.数据存储之SharedPreferences(分享爱好)
- NOIP2014联合权值
- CAS学习笔记(四)