DP

## Code

int maxProfit(int* prices, int pricesSize) {
if(!pricesSize) return 0;
int cur = 0;
int max = 0;
for(int i=1;i<pricesSize;++i){
cur += prices[i]-prices[i-1];
if(cur<0) cur = 0;
else if(cur>max) max = cur;
}
return max;
}

Greedy

## Code

int maxProfit(int* prices, int pricesSize) {
int sum = 0;
for(int i=1;i<pricesSize;++i){
sum += prices[i]-prices[i-1]>0?prices[i]-prices[i-1]:0;
}
return sum;
}

DP

## Code

//打印数组
void printArray(int *array,int len,char *note){
printf("%s\n",note);
for(int i=0;i<len;++i)
printf("%d ",array[i]);
printf("\n");
}

//简化操作
int *simple(int *prices,int *pricesSize){
int i=0;
for(int i=1;i<*pricesSize;++i)
prices[i-1] = prices[i]-prices[i-1];
--(*pricesSize);
//printArray(prices,*pricesSize,"After subtraction:");
bool flag = prices[0]>=0?true:false;
int count = 0;
for(int i=1;i<*pricesSize;++i){
if(flag){
if(prices[i]>=0)
prices[count]+=prices[i];
else{
flag = false;
prices[++count]=prices[i];
}
}else{
if(prices[i]<=0)
prices[count]+=prices[i];
else{
flag = true;
prices[++count]=prices[i];
}
}
}
*pricesSize = count+1;
return prices;
}

//获取当前段最大利润
int maxProfitNow(int *prices,int pricesSize){
int max = 0;
int cur = 0;
for(int i=0;i<pricesSize;++i){
cur += prices[i];
if(cur<0){
cur = 0;
}
max = max>cur?max:cur;
}

return max;
}

//获取最大利润
int maxProfit(int* prices, int pricesSize) {
if(pricesSize==1)   return 0;
//简化
int *simplestPrices = simple(prices,&pricesSize);
//printArray(simplestPrices,pricesSize,"After simple:");
//printf("\n");
int max = 0;

for(int i=0;i<pricesSize;++i){
if(simplestPrices[i]<0){
int tmp = maxProfitNow(simplestPrices,i) + \
maxProfitNow(simplestPrices+i+1,pricesSize-i-1);
max = tmp>max?tmp:max;
//printArray(prices,pricesSize,"Test");
//printf("%d %d--\n",i,tmp);
}
}
int tmp = maxProfitNow(simplestPrices,pricesSize);
max = tmp>max?tmp:max;

return max;
}

## Summary

You may figure it out,that these problems are as the same with “Maximum subarray”.
So in the third solution,I simplify the prices’ array.And use the DP to calculate the maximum result from some maximum subarray.

#### leetcode【121+122+123 best time to buy and sell stock】【python】

2016-09-12 21:04:35

#### [leetcode] 309. Best Time to Buy and Sell Stock with Cooldown 解题报告

2016-06-14 14:53:30

#### Leetcode_122_Best Time to Buy and Sell Stock II

2015-01-26 18:28:17

#### [LeetCode] Best Time to Buy and Sell Stock IV

2015-02-23 00:08:34

#### 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock（最佳买卖股票的时间）】

2015-08-14 06:16:32

#### 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告

2015-04-06 11:10:34

#### LeetCode(188) Best Time to Buy and Sell Stock IV (Java)

2015-04-19 15:45:27

#### LeetCode--Best Time to Buy and Sell Stock III (动态规划）

2014-05-28 11:07:16

#### Leetcode 123 Best Time to Buy and Sell Stock III 至多两次买卖股票最大收益

2015-07-08 23:23:09

#### 【LeetCode】【Python题解】Best Time to Buy and Sell Stock II

2014-07-24 10:11:44

## 不良信息举报

【leetcode】Best Time to Buy and Sell Stock I&II&III