标签:
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:
Example:
prices = [1, 2, 3, 0, 2] maxProfit = 3 transactions = [buy, sell, cooldown, buy, sell]
int maxProfit(int* prices, int pricesSize) { //each time prices[i] has four cases: //1: stock has 0 and do nothing -> has0_donothing // -> prices[i - 1] : 1 or 4 //2: stock has 0 and buy 1 -> has0_buy // -> prices[i - 1] : 1 //3: stock has 1 and do nothing -> has1_donothing // -> prices[i - 1] : 2 or 3 //4: stock has 1 and sell 1 -> has1_sell // -> prices[i - 1] : 2 or 3 // initialize four var int has0_donothing = 0; int has0_buy = -prices[0]; int has1_donothing = -prices[0]; int has1_sell = 0; //if size < 2 return 0 if(pricesSize < 2) return 0; for(int i = 1; i < pricesSize; i++){ has1_donothing = has1_donothing > has0_buy ? has1_donothing : has0_buy; has0_buy = -prices[i] + has0_donothing; has0_donothing = has0_donothing > has1_sell ? has0_donothing : has1_sell; has1_sell = prices[i] + has1_donothing; } // return mast be 1 or 4 return has0_donothing > has1_sell ? has0_donothing : has1_sell; }
Best Time to Buy and Sell Stock with Cooldown
标签:
原文地址:http://www.cnblogs.com/dylqt/p/5118911.html