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)
classSolution {publicintmaxProfit(int[] prices) {if (prices ==null||prices.length<2)return0;int s0 =0; // 0 stocks in hand state after day 1int s1 =-prices[0]; // 1 stock in hand state after day 1int s2 =Integer.MIN_VALUE; // Rest state after day 1 (Not possible)for (int i =1; i <prices.length; ++i) {int last_s2 = s2;// The ith day rest state can only be reached from recent sell// Therefore sell on i-1th day with 1 stock s2 = s1 + prices[i];// If we want 1 stock in our hand at ith day// Either ask i-1th day with 1 stock// OR ask i-1th day with 0 stock and buy 1 stock at ith day s1 =Math.max(s0 - prices[i], s1);// Now we can reach ith day 0 stocks in hand & ready to buy// 1-> Just came from rest state(s2)// 2-> Continue from i-1th day 0 stocks in hand & ready to buy s0 =Math.max(s0, last_s2); }returnMath.max(s0, s2); }}