leetcode--Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.


题意:在数组中,查找一个连续的子数组,使它的元素有最大和,求最大和

分类:数组,动态规划


解法1:很经典的动态规划题目。关键是找到规划关系。

设flag[i],我们知道,每个子数组,都必然以一个元素结尾,所有flag[i]就代表,以元素nums[i]为结尾的子数组的最大和

那么来考虑flag[i+1],对于它只有两种选择,一个是nums[i+1],一个是nums[i+1]+flag[i]

所以关系就是flag[i+1]=Max(nums[i+1],nums[i+1]+flag[i]);

public class Solution {
    public int maxSubArray(int[] nums) {
        int res[] = new int[nums.length];
		int max = nums[0];
		res[0] = nums[0];
		for(int i=1;i<nums.length;i++){
			if(res[i-1]+nums[i]<nums[i]){
				res[i] = nums[i];
			}else{
				res[i] = res[i-1]+nums[i];
			}
			if(max<res[i]){
				max = res[i];
			}
		}
		return max;
    }
}

你可能感兴趣的:(leetcode--Maximum Subarray)