美文网首页
Maximum Subarray

Maximum Subarray

作者: 小明今晚加班 | 来源:发表于2019-02-21 22:13 被阅读0次

    题目描述:

    Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

    Example:

    Input: [-2,1,-3,4,-1,2,1,-5,4],
    Output: 6
    Explanation: [4,-1,2,1] has the largest sum = 6.

    分析从一个数组中,找到某几个连续的值之和最大,并返回。(如果需要记录是哪个连续的数字串的话,只需要在if条件中记录下标即可)
    我的Code如下:

    public int maxSubArray(int[] nums) {
            int sum = nums[0];       
            
            for(int i=0; i<nums.length; i++){
                
                int subSum=0;
                
                for(int j=i; j<nums.length; j++){                
                    subSum+=nums[j];
                    if(subSum > sum){
                        sum = subSum;
                    }
                }
            }
            
            return sum;
        }
    
    

    相关文章

      网友评论

          本文标题:Maximum Subarray

          本文链接:https://www.haomeiwen.com/subject/pwrjyqtx.html