53. Maximum Subarray

来源:互联网 发布:正版办公软件要买吗 编辑:程序博客网 时间:2024/05/08 12:45

题目描述:
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.

java代码:

public class Solution {    public int maxSubArray(int[] nums) {        int length = nums.length;        int[] a = new int[length];        a[0]=nums[0];        for(int i=1;i<length;i++){            if(nums[i]>0)                a[i]=Math.max(a[i-1]+nums[i],nums[i]);            else if(a[i-1]<0)                a[i] = Math.max(a[i-1],nums[i]);            else                a[i]=a[i-1]+nums[i];        }        int max = a[0];        for(int i=1;i<length;i++)            max = Math.max(max,a[i]);        return max;    }}

下面附上几组测试用例:
这里写图片描述
这里写图片描述
这里写图片描述

0 0