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.
解析:求解序列子串的最大和。
方法一:可以举例发现,一旦子串和小于0,则后面的值都会减小,所以在此时把局部最优解值赋为0,重新开始计算。

 class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
          int fmax = nums[0];
          int smax = 0;
            int n = nums.size();
          for(int i=0;i<n;i++)
          {
              smax = smax+nums[i];
              fmax = fmax>smax?fmax:smax;
              if(smax < 0)
                  smax=0;
          }
            return fmax;
        }
    };

方法二:分而治之(divide and conquer).

class Solution {
public:
    int maxSubArray(vector<int>& nums)
    {
        int n = nums.size();
        if(n == 0) return 0;//或者直接用nums.empty()
        return div_ca(nums,0,n-1);
    }
    int div_ca(vector<int>& nums,int left,int right)
    {
        if(left >=right) return nums[left];
        int mid = left + (right - left)/2;//求中间值的下标,注意不是left+right
        int lmax = div_ca(nums,left,mid-1);
        int rmax = div_ca(nums,mid+1,right);
        int mmax = nums[mid],nmax = mmax;
        for(int i= mid-1;i >= left;i--)
        {
            nmax = nmax+nums[i];
            mmax = max(nmax,mmax);
        }
        nmax = mmax;
        for(int j = mid+1;j <= right;j++)
        {
            nmax = nmax+nums[j];
            mmax = max(nmax,mmax);
        }
        return max(mmax,max(lmax,rmax));
    }
};

分治法的基本思想;将一个难以解决的大问题分解为若干个规模相同的小问题,逐个解决,分而治之。
分治策略是:对于一个规模为n的问题,若该问题规模较小,则直接解决,否则将它分解为k个规模较小的子问题,这些子问题相互独立且与原问题形式相同,递归的解决这些子问题,然后将各个子问题的解合并得到原问题的解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值