My concise and simple solution in C++

  • 0

    Reset tmp if the previous subarray sum up to a negative
    class Solution {
    int maxSubArray(vector<int>& nums) {
    int sum = nums[0] ;
    int tmp = 0;
    for (auto x : nums){
    tmp+= x;
    if (tmp > sum) sum = tmp;
    if (tmp<0) tmp = 0;
    return sum;

Log in to reply

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