53. 最大子数组和(中等)

1,问题描述

53. 最大子数组和

难度:中等

给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

子数组是数组中的一个连续部分。

示例 1:

1
2
3
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。

示例 2:

1
2
输入:nums = [1]
输出:1

示例 3:

1
2
输入:nums = [5,4,-1,7,8]
输出:23

提示:

  • 1 <= nums.length <= 10^5
  • -104 <= nums[i] <= 10^4

**进阶:**如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。

2,初步思考

​ 贪心 or 动态规划

3,代码处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class _53最大子数组和 {

// 解法1:贪心算法
public int maxSubArray_greedy(int[] nums) {
int pre = nums[0];
int max = pre;
for (int i = 1; i < nums.length; i++) {
if (pre < 0) {// 丢弃无用的前数据
pre = nums[i];
} else {
pre = pre + nums[i];
}
max = Math.max(max, pre);
}
return max;
}

// 解法2:动态规划
public int maxSubArray_dp(int[] nums) {
int pre = 0;
int max = 0;
for (int x : nums) {
pre = Math.max(pre + x, x);// 状态转移方程:dp[i] = Math.max(dp[i - 1] + nums[i], nums[i])
max = Math.max(max, pre);
}
return max;
}

public static void main(String[] args) {
_53最大子数组和 maxSubArray = new _53最大子数组和();
System.out.println(maxSubArray.maxSubArray_greedy(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
}
}