[LeetCode]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.

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.

翻译:

给你一个整数型数组nums,找出连续的子数组(长度至少为1)使得其和最大,返回这个最大值。

举例:

  输入:[-2,1,-3,4,-1,2,1,-5,4]

  输出:6

  解释:子数组[4,-1,2,1] 具有最大和为6

跟进:

  如果你找到了O(n)的解决方案,尝试使用分治方法来编写另一个解决方案,这是更微妙的解法。

二、分析

(一)暴力解法

  暴力方式就是在数组nums长度范围内以任意位置开始计算任意长度的数组,同时始终记录下最大的那个和,当所有的情况都考虑完后,自然就记录下了最大值。其复杂度为O(n3)。

代码:

 1 int maxSubArray(int* nums, int numsSize) {
 2     int maxSum = nums[0],sum;
 3     for (int i = 0; i < numsSize; i++) {
 4         for (int j = i; j < numsSize; j++) {
 5             sum = 0;
 6             for (int k = i; k <= j; k++)
 7                 sum += nums[k];
 8             if (sum > maxSum)
 9                 maxSum = sum;
10         }
11     }
12     return maxSum;
13 }

猜你喜欢

转载自www.cnblogs.com/wf751620780/p/9285782.html