Simple C++ solution with 8ms


  • -1
    J
    int maxSubArray(vector<int>& nums) {
        int maxSum = nums.front();
        for(int i = 1; i<nums.size(); i++) {
            nums[i] = max(nums[i], nums[i-1] + nums[i]);
            maxSum = max(maxSum, nums[i]);
        }
        
        return maxSum;
    }

  • 0
    D

    You don't need to overwrite the vector. Once you use the value nums[i] you've taken it into account and don't need to store it. My solution is similar but you don't need to store the intermediate values.

    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int curr_mx = 0, mx = std::numeric_limits<int>::min();
            for (int n : nums) {
                curr_mx = max(curr_mx + n, n);
                mx = max(mx, curr_mx);
            }
            return mx;
       } 
    };

Log in to reply
 

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