Loading

LeetCode 53 最大子序和

LeetCode53 最大子序和

题目描述

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

样例

输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

算法分析

  • f[i] 以i结尾的连续子数组的集合
    • 区间长度=1 nums[i]
    • >=2, 很多种情况 [i-1,i ] [i-2, i ] ... [0,i] 提出 i f[i-1] +nums[i];

时间复杂度

Java代码

class Solution {
    static int[] f;
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        f = new int[n];
        f[0] = nums[0];
        int ans = nums[0];
        for(int i = 1; i < nums.length; i++){
            f[i] = Math.max(f[i-1]+nums[i], nums[i]);
            ans = Math.max(f[i], ans);
        }

        return ans;
    }
}
posted @ 2020-11-12 17:04  想用包子换论文  阅读(72)  评论(0)    收藏  举报