A concise c++ solution


  • 1
    S
    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int m = nums[0];
            int s = nums[0]; // s stores the max sum of the substring ending at current character. 
            
            for (int i = 1; i < nums.size(); i ++) {
                // If the max sum of a string ending at prev character is neg, assign s to the value of current number.
                s = (s > 0)? (s + nums[i]): nums[i]; 
                m = max(m, s);
            }
            return m;
        }
    };

Log in to reply
 

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