[Leetcode-53]Maximum Subarray 最大子数组和

0. 题目概要

  • 题目概要
  • 分析
  • AC代码 C
  • AC代码 Java

Leetcode 53. Maximum Subarray
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.

翻译:
一个整数数组, 一个非空的子数组(连续一段数), 使得它的和最大。


1. 分析

线性枚举方法:
[Leetcode-53]Maximum Subarray 最大子数组和_第1张图片

2. AC代码 C++

  • 线性枚举方法:
    [Leetcode-53]Maximum Subarray 最大子数组和_第2张图片
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        size_t n = nums.size();
        int sum = nums[0];
        int answer = nums[0];
        int minSum = min(0, sum);
        for(int i=1; i< n; i++){
            sum += nums[i];
            answer = max(answer, sum - minSum);
            minSum = min(minSum, sum);
        }

        return answer;
    }
};

3. AC代码 Java

  • 线性枚举方法:
    [Leetcode-53]Maximum Subarray 最大子数组和_第3张图片
public class Solution {
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int sum = nums[0];
        int answer = nums[0];
        int minSum = Math.min(0, sum);
        for(int i=1; ireturn answer;
    }
}

你可能感兴趣的:(动态规划,leetcode,动态规划)