zoukankan      html  css  js  c++  java
  • LeetCode: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.

    思路:採用分治的策略。

    计算左半部分的子集和的最大值,再计算右半部分子集和的最大值,再计算跨越左右两部分子集和的最大值。

    求出的三个值中最大的一个就是要求的最大和。


    代码:

    int Solution::maxSubArray(int A[], int n)
    {
       return calculateMax(A,0,n-1);
    }
    
    int Solution::calculateMax(int A[],int left,int right)
    {
        if(left == right)
            return A[left];
        int mid = (left + right) / 2;
        int subleft_max = calculateMax(A,left,mid);
        int subright_max = calculateMax(A,mid+1,right);
        int sum = A[mid];
        int left_max = A[mid];
        int i;
        for(i = mid-1;i >= left;i--)
        {
            sum = sum + A[i];
            if(sum > left_max)
                left_max = sum;
        }
        sum = A[mid+1];
        int right_max = A[mid+1];
        for(i = mid+2;i <= right;i++)
        {
            sum = sum + A[i];
            if(sum > right_max)
                right_max = sum;
        }
        int temp;
        if(subleft_max > subright_max)
            temp = subleft_max;
        else
            temp = subright_max;
        if(temp > (left_max + right_max))
            return temp;
        else
            return left_max + right_max;
    }
    


  • 相关阅读:
    费马小定理
    Big Number阶乘位数计算(斯特林公式)
    V
    矩阵快速幂求斐波那契
    奇迹
    缘分
    求导
    拓扑排序
    线段树
    单调栈
  • 原文地址:https://www.cnblogs.com/llguanli/p/6872842.html
Copyright © 2011-2022 走看看