给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和
https://leetcode-cn.com/problems/maximum-subarray/
进阶:如果你已经实现复杂度为 O(n)
的解法,尝试使用更为精妙的 分治法 求解
示例1:
示例2:
示例3:
示例4:
示例 5:
提示:
Java解法
package sj.shimmer.algorithm.m2;
/**
* Created by SJ on 2021/2/24.
*/
class D31 {
public static void main(String[] args) {
System.out.println(maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
}
public static int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = nums[0];
int length = nums.length;
int temp = 0;
for (int i = 0; i < length; i++) {
temp = nums[i];
if (max <= temp) {
max = temp;
}
for (int j = i + 1; j < length; j++) {
temp = temp + nums[j];
if (max <= temp) {
max = temp;
}
}
}
return max;
}
}
官方解
https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-by-leetcode-solution/
-
动态规划
- 时间复杂度:O(n)
- 空间复杂度: O(1)
线段树:新概念,暂时不了解了 0.0