C++ solution. I love C++


  • 0
    T
    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int n = nums.size();
            vector<int> array(n+1, 0);
            int i;
            int max = -9999999; // containing at least one number
            for(i=1; i<=n; i++)
            {
                array[i] = array[i-1] + nums[i-1];
                if(nums[i-1] > max)
                    max = nums[i-1];
            }
                
            int low=array[0];
            int profit=0;
            for(i=1; i<=n; i++)
            {
                if(array[i] - low > profit)
                    profit = array[i] - low;
                if(array[i] < low)
                    low = array[i];
            }
            
            if(max < 0)
                return max;
            else 
                return profit;
        }
    };

Log in to reply
 

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