A question about Best Time to Buy and Sell Stock II


  • 1
    C

    Given data as following: [1,2,3,4,5], the expected answer is 4, but I think the correct answer should be 6, because we can buy 1 and 2, then sell them on price 4 and 5, total profit is (4-1)+(5-2)=6. So anyone can help me clarify this doubt?
    My code for your reference:

    int max = 0;
    public int maxProfit(int[] prices) {
        if (prices.length==0) return 0;
        search(0, 0, 0, prices, prices.length);
        return max;
    }
    
    public void search(int dep, int p, int flag, int[] prices, int n) {
        if(dep == n) {
            if (p>max) {
                max = p;
                return;
            }
        }else {
            /* -1:buy, 0:nothing, 1:sell*/
            
            for (int i=-1; i<=1; i++) {
                if (i==-1) {
                    flag += i;
                    p -= prices[dep];
                    search(dep+1, p, flag, prices, n);
                    p += prices[dep];
                    flag -= i;
                }else if (i==1 && flag < 0) {
                	flag+=i;
                    p += prices[dep];
                    search(dep+1, p, flag, prices, n);
                    p -= prices[dep];
                    flag-=i;
                }else if(i==0) {
                    search(dep+1, p, flag, prices, n);
                }
    
            }
        }
    }

  • 1
    L

    See the problem carefully: you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    You can't hold 1 and 2 at the same time.


Log in to reply
 

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