Why the system would say my code returns wrong answer?


  • 0
    Q

    For the Best Time to Buy and Sell Stock II problem, I can't figure out why my code returns wrong answer for [1, 2] from the OJ system.

    On my machine, it returns 1. But the leetcode judgement system says my output is 2.

    int maxProfit(vector<int>& prices) {
        int size = prices.size();
    
        if (size <= 1)
        {
            return 0;
        }
    
        int max = 0;
    
        for (int i = size - 1; i >= 0; --i)
        {
            int diff = 0, j = i - 1;
    
            for ( ; i >= 0; --j)
            {
                if (prices[j] > prices[j + 1])
                {
                    j++;
                    break;
                }
    
                diff = prices[i] - prices[j];
            }
    
            max += diff;
            i = j;
        }
    
        return max;
    }

Log in to reply
 

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