LeetCode-Maximum Subarray

Description:
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.

Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

题意:给定一个由整形构成的数组,要求输出连续的几个整数之和最大的值;

第一种解法:使用暴力破解,遍历所有可能的情况,找出最大的那个值;

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length == 1){
            return nums[0];
        }//只有一个元素的数组,最大值即为本身
        int maxSum = Integer.MIN_VALUE;//记录最大值
        for(int i=0; i<nums.length; i++){
            int sum = nums[i];//从此节点开始的最大值
            maxSum = sum > maxSum ? sum : maxSum;
            for(int j=i+1; j<nums.length; j++){
                sum += nums[j];
                maxSum = sum > maxSum ? sum : maxSum;
            }
        }
        return maxSum;
    }
}

第二种解法:采用动态规划的思想,维护一个全局最优解和一个局部最优解;在局部最优解中lMaxSum = Max(lMaxSum+nums[i], nums[i]),即如果当前元素比当前元素加局部最优解还要大,那就从当前元素开始重新加;在全局最优解中,gMaxSum = Max(lMaxSum, gMaxSum);

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length == 1){
            return nums[0];
        }//只有一个元素的数组,最大值即为本身
        int gMaxSum = nums[0];//全局最优解
        int lMaxSum = nums[0];//局部最优解
        for(int i=1; i<nums.length; i++){
            lMaxSum = lMaxSum+nums[i] > nums[i] ? lMaxSum+nums[i] : nums[i];
            gMaxSum = lMaxSum > gMaxSum ? lMaxSum : gMaxSum;
        }
        return gMaxSum;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/80910807