Day31 最大子序和

給定一個(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/

  1. 動(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)
  2. 線段樹:新概念,暫時(shí)不了解了 0.0

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容