A 10ms C++ approach


  • 0
    Y
    class Solution {
    public:
    	int maxSubArray(vector<int>& nums) {
    		int j=0,msum,sum,neg=nums[0];
    		while(nums[j]<=0&&j<nums.size()) {
    			neg=(neg>nums[j])?neg:nums[j];j++;
    		}
    		if(j==nums.size()) return neg;
    		sum=msum=nums[j];
    		for(int i=j+1;i<nums.size();){
    			if(nums[i]>=0) {sum+=nums[i];i++;}
    			if(nums[i]<0) {
    				msum=(msum>sum)?msum:sum;
    				while(nums[i]<=0) {
    					sum+=nums[i];
    					i++;
    				}
    				if(sum<0) sum=0;
    			}
    		}
    		return msum=(msum>sum)?msum:sum;;
    	}
    };

Log in to reply
 

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