Maximum Subarray(53) - easy

53— Maximum Subarray

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

Example1:

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

思路1:

分析题目:

  • 如果数组全部为负数, 最长子串值为一个元素,即最大负数.
  • 如果数组中存在正整数, 那么最长子串值一定是从一个正整数开始的子串累加值.
  • 一个子串结束的条件为: 从子串开头元素开始, 向后遍历, 累加起来, 如果累加的结果小于0, 则退出循环, 循环过程中记录最长子串值.
  • 遍历完整个数组, 其中可能出现多个子串, 但在这形成这些子串过程中, 最大子串值被记录下来.

C++代码:

class Solution {
public:
  int maxSubArray(vector<int>& nums) {
    int len = nums.size();
    if(len < 1) return 0;

    int tmp = 0;
    int result = nums[0]-1;
    int i = 0;
    while(i < len){
      if(nums[i] < 0) {
        result = max(result,nums[i]);
        i++;
      }else if(nums[i] >= 0) {
        //子串开始
        do {
          tmp += nums[i];
          result = max(result, tmp);
          i++;
        }while(tmp >= 0 && i < len);
        tmp = 0;
      }
    }
    return result;
  }
};

整理代码为如下形式:

class Solution {
public:
   int maxSubArray(vector<int> &nums) {
    int result = nums[0],sum = 0;
    if(nums.size() < 1) return 0;
    for(int i = 0; i < nums.size() ;i++) {
      sum += nums[i];
      result = max(result, sum);
      sum = max(sum,0); //sum 小于0时, 重置sum
    }
    return result;
  }
};

Complexity Analysis:

Time complexity : O( n n n).
Space complexity : O( 1 1 1).

思路2:

  • 动态规划:
  • 如果最长子串值的子串以nums[i] 结尾, 那么以nums[i]结尾的最长子串值为max(nums[i], max[i-1] + nums[i]); 遍历过程中记录最长子串值.
  //动态规划
  int maxSubArray(vector<int>& nums) {
    int len = nums.size();
    if(len < 1) return 0;
    vector<int> table(len,0);
    int result;

    table[0] = nums[0];
    result = table[0];
    for(int i = 1; i < len; i++) {
      table[i] = max(nums[i], table[i-1]+nums[i]);
      result = max(result, table[i]);
    }
    return result
  }

Complexity Analysis:

Time complexity : O( n n n).
Space complexity : O( 1 1 1).

你可能感兴趣的:(Leetcode,Alorithm,C++,动态规划)