[Concise 7 lines C++] Easy to understand, O(n) time O(1) space DP


  • 0
    H
    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int res = nums[0], pre = nums[0];
            for (int i = 1; i < nums.size(); ++i) {
                if (pre > 0) pre += nums[i];
                else pre = nums[i];
                res = max(res, pre);
            }
            return res;
        }
    };
    

Log in to reply
 

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