給定一個(gè)整數(shù)數(shù)組 nums ,找到一個(gè)具有最大和的連續(xù)子數(shù)組(子數(shù)組最少包含一個(gè)元素),返回其最大和
https://leetcode-cn.com/problems/maximum-subarray/
進(jìn)階:如果你已經(jīng)實(shí)現(xiàn)復(fù)雜度為 O(n) 的解法,嘗試使用更為精妙的 分治法 求解
示例1:
輸入:nums = [-2,1,-3,4,-1,2,1,-5,4]
輸出:6
解釋:連續(xù)子數(shù)組 [4,-1,2,1] 的和最大,為 6 。
示例2:
輸入:nums = [1]
輸出:1
示例3:
輸入:nums = [0]
輸出:0
示例4:
輸入:nums = [-1]
輸出:-1
示例 5:
輸入:nums = [-100000]
輸出:-100000
提示:
1 <= nums.length <= 3 * 104-105 <= nums[i] <= 105
Java解法
思路:
- 求連續(xù)最大值,采用遍歷處理,記錄臨時(shí)值,比較得出最大值
- 這是道簡(jiǎn)單題?我腦子一定銹掉了有什么優(yōu)化算法不記得
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;
}
}

image
官方解
https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-by-leetcode-solution/
-
動(dòng)態(tài)規(guī)劃
腦子果然糊了,官方解也是這種寫法,但是關(guān)鍵的一步我思考出錯(cuò)導(dǎo)致嵌套了循環(huán)
public static int maxSubArray2(int[] nums) { int pre = 0, maxAns = nums[0]; for (int x : nums) { pre = Math.max(pre + x, x);//該位置的值大于前面數(shù)值之和時(shí),棄掉前方元素即可 maxAns = Math.max(maxAns, pre); } return maxAns; }- 時(shí)間復(fù)雜度:O(n)
- 空間復(fù)雜度: O(1)
線段樹:新概念,暫時(shí)不了解了 0.0