C++ Simple Fast O(N) Solution


  • 0
    W
    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int M = nums[0];
            int previous = nums[0];  // Maximum subarray ending with nums[i]
            for (int i = 1; i < nums.size(); i++) {
                previous = max(previous + nums[i], nums[i]);
                if (previous > M)  M = previous;
            }
            return M;
        }
    };
    

Log in to reply
 

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