题目描述
思路分析
代码一:
例如
public static int maxSubArray2(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int res = nums[0];
for (int i = 1; i < nums.length; i++) {
if (dp[i - 1] < 0) {
dp[i] = nums[i];
} else {
dp[i] = nums[i] + dp[i - 1];
}
res = Math.max(res, dp[i]);
}
return res;
}
代码二:
public static int maxSubArray3(int[] nums) {
int max = nums[0];
int sum = nums[0];
for (int i = 1; i < nums.length; i++) {
sum = Math.max(nums[i], sum + nums[i]);
max = Math.max(max, sum);
}
return max;
}
代码三:
public static int maxSubArray(int[] nums) {
int n = nums.length, maxSum = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i - 1] > 0) {
nums[i] += nums[i - 1];
}
maxSum = Math.max(nums[i], maxSum);
}
return maxSum;
}
代码四:
public static int maxSubArray1(int[] nums) {
int ans = nums[0];
int sum = 0;
for (int num : nums) {
if (sum > 0) {
sum += num;
} else {
sum = num;
}
ans = Math.max(ans, sum);
}
return ans;
}