一、题目描述
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
二、题解
方法一:dp
- 定义状态:
- 表示位置 i 的 MS。
- 思考状态转移方程:
- 思考初始化:
- 思考输出:
- 空间压缩:是可以的,只是我不想在想了。
public int maxSubArray(int[] nums) {
final int N = nums.length;
int[] dp = new int[N];
dp[0] = nums[0];
int max = nums[0];
for (int i = 1; i < N; i++) {
dp[i] = Math.max(dp[i-1] + nums[i], nums[i]);
max = Math.max(max, dp[i]);
}
return max;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
方法二:暴力法
做到后面,都不想用暴力了,一开始就用 dp,这里给出暴力的做法:
- 使用双层循环,穷举所有的子区间;
- 对每个子区间内的所有元素求和,得出最大和;
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,