Most intuitive solution for me so far. No Global or no Local.


  • -2
    M

    There can be atmost k buys and k sells. Keep track of maximum value until nth sell and nth buy. No global no local needed. very intuitive one. nth sell value depends on (n)th buy. nth Buy depends on (n-1)th sell

    public int maxProfit(int k, int[] prices) {
    int len = prices.length;

    	if (len < 2 || k <= 0)
    		return 0;
    		 if (k >= len / 2) return quick(prices);
            int[] buy=new int[k];
            Arrays.fill(buy,Integer.MIN_VALUE);
            int[] sell=new int[k];
            for(int i:prices){    
                 for(int j=k-1;j>=0;j--){
                     if(j==0){
                         sell[j]=Math.max(sell[0],buy[0]+i);
                         buy[0]=Math.max(buy[0],-i);
                     }else{
                sell[j] = Math.max(sell[j], buy[j]+i);     
                buy[j]   = Math.max(buy[j],    sell[j-1]-i);  
                }    
                 }
                    
            }
            return sell[k-1]; 
    
    }
    
    private int quick(int[] prices) {
            int len = prices.length, profit = 0;
            for (int i = 1; i < len; i++)
                     if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
            return profit;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.