给你一个整数数组 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 <=
1
0
5
10^5
105
-
1
0
4
10^4
104 <= nums[i] <=
1
0
4
10^4
104
进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。文章来源:https://www.toymoban.com/news/detail-586706.html
题解
// https://leetcode.cn/problems/maximum-subarray/
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Solution {
public int maxSubArray(int[] nums) {
//初始化
int sum = nums[0];
int ans = nums[0];
//遍历整个数组
for (int i = 1; i < nums.length; i++) {
//更新sum
sum = Math.max(sum + nums[i], nums[i]);
//比较之前和和最大值
ans = Math.max(ans, sum);
}
return ans;
}
//贪心
public int maxSubArray2(int[] nums) {
//初始化
int ans = nums[0];
int sum = 0;
for(int num: nums) {
//sum:之前和 如果大于,则更新为当前值num+sum
if(sum > 0) {
sum += num;
}
//sum:之前和 如果小于,则更新为当前值num
else {
sum = num;
}
//比较之前和和最大值
ans = Math.max(ans, sum);
}
return ans;
}
//动态规划
public int maxSubArray3(int[] nums) {
int n = nums.length;
for (int i = 1; i < n; i++) {
if(nums[i-1]>0){
nums[i] += nums[i-1];
}
}
return Arrays.stream(nums).max().getAsInt();
}
@Test
public void test() {
Solution s = new Solution();
assertEquals(6, s.maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
assertEquals(1, s.maxSubArray2(new int[]{1}));
assertEquals(23, s.maxSubArray3(new int[]{5, 4, -1, 7, 8}));
}
}
分治:文章来源地址https://www.toymoban.com/news/detail-586706.html
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class Solution2 {
public int maxSubArray(int[] nums) {
return maxSubArrayPart(nums, 0, nums.length - 1);
}
private int maxSubArrayPart(int[] nums, int left, int right) {
if (left == right) {
return nums[left];
}
int mid = (left + right) / 2;
return Math.max(
maxSubArrayPart(nums, left, mid),
Math.max(
maxSubArrayPart(nums, mid + 1, right),
maxSubArrayAll(nums, left, mid, right)
)
);
}
//左右两边合起来求解
private int maxSubArrayAll(int[] nums, int left, int mid, int right) {
int leftSum = Integer.MIN_VALUE;
int sum = 0;
for (int i = mid; i >= left; i--) {
sum += nums[i];
if (sum > leftSum) {
leftSum = sum;
}
}
sum = 0;
int rightSum = Integer.MIN_VALUE;
for (int i = mid + 1; i <= right; i++) {
sum += nums[i];
if (sum > rightSum) {
rightSum = sum;
}
}
return leftSum + rightSum;
}
@Test
public void test() {
Solution2 s = new Solution2();
assertEquals(6, s.maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
assertEquals(1, s.maxSubArray(new int[]{1}));
assertEquals(23, s.maxSubArray(new int[]{5, 4, -1, 7, 8}));
}
}
到了这里,关于【力扣】53. 最大子数组和的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!