【leetcode】53. Maximum Subarray

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/81326641

原题链接

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.

我的代码(指路-》大神的题解

思路:用的最简单的遍历求和sum,与最大值maxSum比较并记录。(刚开始写的时候觉得时间复杂度O(n2)会是坑点,但是时间好像没卡我)

           maxSum初始比较值应该是int的最小值 即1<<31(-2147483648)

int maxSubArray(vector<int>& nums) {
         int len = nums.size();
         int maxSum = 1<<31;//boundary
         int sum = 0;
         int i = 0;
         int j = 0;
          for(i = 0; i < len; i++){
               sum = nums[i];
              if(sum > maxSum) maxSum = sum;
              for(j = i + 1;j < len ;j++){
                   sum += nums[j];
                  if(sum > maxSum) maxSum = sum;
        }
    }
          return maxSum;
    }

附完整调试代码

//
// Created by maotianyi on 2018/8/1.
//

#include<iostream>
#include <cstdio>
#include <vector>
using namespace std;


int main(){
    vector<int> nums = {1};
    int len = nums.size();
 
    int maxSum = 1<<31;//boundary

    int sum = 0;
    printf("%d\n",maxSum);
    int i = 0;
    int j = 0;
    for(i = 0; i < len; i++){
        sum = nums[i];
        if(sum > maxSum) maxSum = sum;
        for(j = i + 1;j < len ;j++){
            sum += nums[j];
            if(sum > maxSum) maxSum = sum;
        }
    }

    printf("%d",maxSum);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/81326641