You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 7
class Solution {
public int[] trade( int day, int[] prices ){
if( day == 0){
int[] res = { -prices[0], 0 };
return res;
}
int[] prev = trade( day-1, prices );
int prevHold = prev[0], prevNotHold = prev[1];
int hold = Math.max(prevHold, prevNotHold - prices[day] );
int notHold = Math.max(prevNotHold, prevHold + prices[day] );
int[] res = {hold, notHold};
return res;
}
public int maxProfit(int[] prices) {
int[] res = trade( prices.length - 1, prices );
return res[1];
}
}