privatestaticclassSolution{ publicintmaxSubArray(int[] nums){ int max = nums[0]; int curMax = 0; for (int i = 0; i < nums.length; i++) { curMax = nums[i]; for (int j = i + 1; j <= nums.length; j++) { if (curMax > max) { max = curMax; } if (j != nums.length) { curMax += nums[j]; }
} } return max; } }
动态规划
1 2 3 4 5 6 7 8 9 10 11 12
privatestaticclassSolution2{ publicintmaxSubArray(int[] nums){ int max = nums[0];
for (int i = 1; i < nums.length; i++) { nums[i] += Math.max(nums[i - 1], 0); max = Math.max(max, nums[i]); } return max; }