• LeetCode 53. Maximum Subarray


    53. Maximum Subarray

    my program:

    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int result = nums[0];
            int sum = 0;
            for (int i = 0; i<nums.size(); ++i)
            {
                sum = 0;
                for (int j = i; j<nums.size();++j)
                {
                    sum += nums[j];
                    if (sum > result)   result = sum;
                }
            }
            return result;
        }
    };

    Submission Result: Time Limit Exceeded

    这个就是所谓的蛮力法吧…….%>_<%
    时间复杂度是O(n2),当数据集越大,执行所需的时间就成平方数量级的增长,所以计算所需的时间超出了规定的时间,无法AC.

    分治算法

    首先将其分成两半A[l..m]和A[m+1..r],其中m=(l+r)/2,并分别求递归求出这两半的最大子串和

    中间middle部分是两个循环,分别找出左边和右面(包含m点)的最大子串和.

    最后取left ightmiddle中最大值

    程序如下:

    class Solution {
    public:
        int solve(vector<int>& nums, int begin, int end)
        {
            if (begin == end) return nums[begin];
            int mid = (begin+end) / 2;
            int leftMax = solve(nums, begin, mid);
            int rightMax = solve(nums, mid+1, end);
            int midLeftMax = nums[mid];
            int sumMidLeft = nums[mid];
            for (int i = mid-1; i>=begin; --i)   
            {
                sumMidLeft += nums[i];
                midLeftMax = max(midLeftMax, sumMidLeft);
            }
            int midRightMax = nums[mid];
            int sumMidRight = nums[mid];
            for (int j = mid+1; j<=end; ++j)  
            {
                sumMidRight += nums[j];
                midRightMax = max(midRightMax, sumMidRight);
            }
            return max(max(leftMax, rightMax),midLeftMax+midRightMax-nums[mid]);
        }
        int maxSubArray(vector<int>& nums) {
          return solve(nums, 0, nums.size()-1);
        }
    };

    Simplest and fastest O(n) C++ solution:

    Idea is very simple. Basically, keep adding each integer to the sequence until the sum drops below 0.
    If sum is negative, then should reset the sequence.

    class Solution {
    public:
        int maxSubArray(int A[], int n) {
            int ans=A[0],i,j,sum=0;
            for(i=0;i<n;i++){
                sum+=A[i];
                ans=max(sum,ans);
                sum=max(sum,0);
            }
            return ans;
        }
    };

    此算法的时间复杂度是O(n),当数据非常大的时候,比起时间复杂度是O(n2)的算法好的不是一点.

  • 相关阅读:
    java中清空session
    freemarker中修改和添加功能中包含checkbox复选框默认选中需求的解决方式
    Highcharts动态赋值学习
    CSDN Luncher
    JS导入导出Excel表格的方法
    js 下载文件的操作方法
    模板标签的作用
    css3的calc()
    JS滚轮mousewheel事件和DOMMouseScroll事件
    css BFC(格式化上下文)的理解
  • 原文地址:https://www.cnblogs.com/yangjiannr/p/7391356.html
Copyright © 2020-2023  润新知