Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
[−2,1,−3,4,−1,2,1,−5,4]
,the contiguous subarray
[4,−1,2,1]
has the largest sum = 6
.
对于sum[i] 最大的情况有两种 一种是和前边其他的数一起组成最大 一中是单独自己组成最大 所以每次sum[i] 要判定哪个大就取哪个作为sum[i] 的值
state:sum[i]表示 largest sum
initial sum[0] = nums[0]
function: sum[i] = Math.max(sum[i-1] + nums[i], nums[i]) max = math.max(max, sum[i])
return max
时间复杂度为O(n)
时间复杂度为O(n)
public class Solution { public int maxSubArray(int[] nums) { if (nums.length == 0) { return 0; } int len = nums.length; int[] sum = new int[len]; int max = nums[0]; sum[0] = nums[0]; for (int i = 1; i < len; i++) { sum[i] = Math.max(sum[i - 1] + nums[i], nums[i]); max = Math.max(max, sum[i]); } return max; } }
没有评论:
发表评论