Leetcode 122 Best Time to Buy and Sell Stock II Solution in java | Hindi Coding Community

0

 


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];
    }
}

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !