刷题顺序以及题解分析参考卡哥的代码随想录
题目描述
英文版描述
Given an integer array nums
, find the
subarray
with the largest sum, and returnits sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Example 2:
Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1.
Example 3:
Input: nums = [5,4,-1,7,8] Output: 23 Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
Constraints:
1 <= nums.length <= 10^5
-10(4) <= nums[i] <= 10^4
英文版地址
中文版描述
给你一个整数数组 nums
,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
子数组 是数组中的一个连续部分。
示例 1:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6 。
示例 2:
输入: nums = [1] 输出: 1
示例 3:
输入: nums = [5,4,-1,7,8] 输出: 23
提示:
1 <= nums.length <= 10^5
-10(4) <= nums[i] <= 10^4
中文版地址
解题方法
class Solution {
public int maxSubArray(int[] nums) {
// dp[i] 代表整数数组nums [0,i]范围内的最大连续数组和(必须包含nums[i])
int[] dp = new int[nums.length];
int result = 0;
dp[0] = nums[0];
result = nums[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
result = Math.max(result, dp[i]);
}
return result;
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是数组的元素数
- 空间复杂度:O(n)