leetcode 53. Maximum Subarray

来源:互联网 发布:网络协议各层的功能 编辑:程序博客网 时间:2024/06/05 04:30
//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.public class test{    public static int maxSubArray(int[] nums) {    int totalMax = Integer.MIN_VALUE;    int max = Integer.MIN_VALUE;    for(int i = 0;i<nums.length;i++){    if(max<0){    max = 0;    }    max = max+nums[i];    if(totalMax<max){    totalMax = max;    }    }        return totalMax;    }    public static void main(String[] args){int[] nums = {-2,1,-3,4,-1,2,1,-5,4};int result = maxSubArray(nums);System.out.println(result);}}

0 0
原创粉丝点击