Equivalent code, one AC, other run time error


  • 0
    G

    I think the following code pieces are equivalent. But the first one got run time error but the second one passed. (The if statement should have 1 instead of 0 in condition, but I don't think that matters)

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int sum=0;
            for (int i=0; i<prices.size()-1; i++){
                sum += max(prices[i+1]-prices[i], 0);
            }
            return sum;
        }
    };
    
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if (prices.size() == 0){
                return 0;
            }
            int sum=0;
            for (int i=0; i<prices.size()-1; i++){
                sum += max(prices[i+1]-prices[i], 0);
            }
            return sum;
        }
    };

Log in to reply
 

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