Skip to content

Commit 11d5198

Browse files
committed
309. Best Time to Buy and Sell Stock with Cooldown
1 parent 4c944b0 commit 11d5198

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
2+
3+
class Solution {
4+
public:
5+
int maxProfit(vector<int>& prices) {
6+
if(prices.size()==1) return 0;
7+
vector<int>result(prices.size(),0);
8+
result[0]=0;
9+
if(prices.size()>1) result[1]=max(0,prices[1]-prices[0]);
10+
if(prices.size()>2) result[2]=max(0,max(result[1],max(prices[2]-prices[0],prices[2]-prices[1])));
11+
for(int i=3;i<prices.size();i++){
12+
for(int j=0;j<i;j++){
13+
if(j>=2) result[i]=max(result[i],max(result[i-1],prices[i]-prices[j]+result[j-2]));
14+
else result[i]=max(result[i],max(result[i-1],prices[i]-prices[j]));
15+
}
16+
}
17+
return result[prices.size()-1];
18+
}
19+
};

0 commit comments

Comments
 (0)