Complexity(n), O(1) Space, C++

  • 0

    After considering the base case, the idea is pretty straightforward: temp works as a counter, it is always compared with res to output max value.

    More importantly, the program will set count to zero when next element is even greater than the res (greatest sum so far)

    I hope this would give you some ideas about this question, thanks.

    class Solution {
        int maxSubArray(vector<int>& nums) {
        int res= nums[0],temp=nums[0];
            if (nums.size() == 1) return nums[0];
        for (int i = 1; i<nums.size(); i++){
            res = max (res, temp);
            temp += nums[i];
            if (nums[i] > temp) {
                temp = nums[i];
        res = max (res, temp);
        return res;

Log in to reply

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