4 lines C++ solution with explanation


  • 3

    Use two values. One is used for catch the current contiguous sum till i-th number in the array. The another one is used for store the maximum contiguous sum till i-th number in the array.

    int maxSubArray(vector<int>& nums) {
            int cur_val = 0, maxv = INT_MIN;
            for(auto i:nums)
                cur_val = max(i,cur_val+i), maxv = max(maxv, cur_val);
            return maxv;
        }
    

Log in to reply
 

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