欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

lintcode-41. Maximum Subarray

程序员文章站 2022-03-24 17:41:20
...

1. 问题描述

Description

Given an array of integers, find a contiguous subarray which has the largest sum.

The subarray should contain at least one number.

2. my solution

2.1 我的思路

因为是连续的, 所以想到位置不断向前移动,和小于0更新位置, 记录最大和的方法

2.2 代码实现

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        // write your code here
        int sum = 0;
        int maxSum = nums[0];
        
        for (int i = 0;i<nums.length ;i++ ) 
        {
            sum += nums[i];
            if(sum>maxSum)
                maxSum = sum;
            else if(sum<=0) sum = 0;
        }
        return maxSum;
    }
}

2.3 运行结果

lintcode-41. Maximum Subarray

3. others solutions

3.1 思路一(较好)

public class Solution {
    public int maxSubArray(int[] A) {
        if (A == null || A.length == 0){
            return 0;
        }
        //max记录全局最大值,sum记录前i个数的和,minSum记录前i个数中0-k的最小值
        int max = Integer.MIN_VALUE, sum = 0, minSum = 0;
        for (int i = 0; i < A.length; i++) {
            sum += A[i];
            max = Math.max(max, sum - minSum);
            minSum = Math.min(minSum, sum);
        }

        return max;
    }
}

lintcode-41. Maximum Subarray