最长子序列和

版权声明:本文为博主原创文章,转载请注明出处。个人博客地址:https://yangyuanlin.club/ 欢迎来踩~~~~ https://blog.csdn.net/w7239/article/details/84727414
  • 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.

    More practice:

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

  • 题目大意:求最长子序列和。给定一个至少包含一个数字的数组,查找最长子序列和。

    例如:给定的是数组[−2, 1, −3, 4, −1, 2, 1, −5, 4],最大连续子序列是[4, -4, 2, 1],最长子序列和是6。

    更多练习:如果已经找到O(n)解决方案,尝试使用分治法解决方案。

  • 思路:maxSum 必然是以A[i](取值范围为A[0] ~ A[n-1])结尾的某段构成的,也就是说maxSum的candidate必然是以A[i]结果的。如果遍历每个candidate,然后进行比较,那么就能找到最大的maxSum了。
    假设把A[i]之前的连续段叫做sum。可以很容易想到:
    (1)如果sum>=0,就可以和A[i]拼接在一起构成新的sum。因为不管nums[i]多大,加上一个正数总会更大,这样形成一个新的candidate。
    (2)反之,如果sum<0,就没必要和A[i]拼接在一起了。因为不管A[i]多小,加上一个负数总会更小。此时由于题目要求数组连续,所以没法保留原sum,所以只能让sum等于从A[i]开始的新的一段数了,这一段数字形成新的candidate。
    (3)如果每次得到新的candidate都和全局的maxSum进行比较,那么必然能找到最大的max sum subarray.在循环过程中,用maxSum记录历史最大的值。从A[0]到A[n-1]一步一步地进行。

  • 代码:

#include<iostream>
using namespace std;
int maxSubArray(int A[], int n)
{
    if(n == 0)return 0;
    int sum = A[0], maxsum = A[0];
    for(int i=1; i<n; i++)
    {
        if(sum >= 0)
        {
            sum += A[i];
        }
        else
        {
            sum = A[i];
        }
        maxsum = max(sum, maxsum);
    }
    return maxsum;
}
int main()
{
    int A[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    cout<<maxSubArray(A, 9)<<endl;
    return 0;
}
  • 以上。

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


猜你喜欢

转载自blog.csdn.net/w7239/article/details/84727414