Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
int maxProfit(int* prices, int pricesSize) {
int *max = (int *)malloc(sizeof(int)*pricesSize);
int i,j;
int tmp;
memset(max,0,sizeof(int)*pricesSize);
if(prices == NULL || pricesSize == 0){
return 0;
}
for(i = 1;i < pricesSize;++i){
max[i] = max[i-1];
for(j = 0;j < i;++j){
tmp = prices[i] - prices[j];
if(j >= 2){
tmp += max[j-2];
}
max[i] = tmp > max[i]?tmp:max[i];
}
}
return max[pricesSize-1];
}