leetcode解题方案--053--Maximum Subarray

来源:互联网 发布:系统更新软件 编辑:程序博客网 时间:2024/06/17 03:03

题目

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

分析

动态规划思想,每个dp数组记录以i为子字符串尾的字符串和。取最大即可。

题目中有说分治的,不太清楚什么意思

class Solution {     public static int maxSubArray(int[] nums) {        int max = nums[0];        int last = nums[0];        for (int i = 1; i < nums.length; i++) {            last = last > 0 ? last + nums[i] : nums[i];            max = last > max ? last : max;        }        return max;    }}
原创粉丝点击