Fork me on GitHub

53. Maximum Subarray

class Solution {
    public int maxSubArray(int[] nums) {
    	int ans = nums[0] ;
        int n = nums.length;
        int flag [] = new int[n];
    	flag[0] =  nums[0];
    	for (int i = 1 ; i < n ; i++ ) {
    		flag[i] = Math.max( flag[i-1] + nums[i],nums[i]);
    		ans = Math.max(flag[i],ans);
    	}
        return ans;
    }
}

改进:

class Solution {
    public int maxSubArray(int[] nums) {
    	int ans = nums[0] ;
        int n = nums.length;
        int flag  =  nums[0];
    	for (int i = 1 ; i < n ; i++ ) {
    		flag = Math.max( flag + nums[i],nums[i]);
    		ans = Math.max(flag,ans);
    	}
        return ans;
    }
}

C

int maxSubArray(int* nums, int size)
{
    int sum = 0 ;
    int max = INT_MIN;
    for (int i = 0 ; i < size ; i++){
        if(sum>=0) sum += nums[i];
        else sum = nums[i];
        if(sum>max) max = sum;
    }
    return max;
}

Python

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max = nums[0]
        sum = nums[0]
        for i in range(1,len(nums)):
            if sum>=0:
                sum = sum + nums[i]
            else :
                sum = nums[i]
            if(max < sum):
                max = sum
        return max
posted @ 2019-09-04 11:55  cznczai  阅读(136)  评论(0编辑  收藏  举报