第58题 Maximum Subarray

来源:互联网 发布:可以听pdf的软件 编辑:程序博客网 时间:2024/06/02 07:29

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.

click to show more practice.

Hide Tags
 Divide and Conquer Array Dynamic Programming
Solution in Java:
public class Solution {    public int maxSubArray(int[] nums) {        if(nums.length==0) return Integer.MIN_VALUE;        int[] opj = new int[nums.length];        int max = nums[0];        opj[0]= nums[0];        for(int i=1; i<nums.length; i++){            opj[i] = opj[i-1]+nums[i]>nums[i]?opj[i-1]+nums[i]:nums[i];            max = Math.max(opj[i], max);        }        return max;    }}


0 0