• 【LeetCode】053. 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.

    题解:

      由于是连续子序列这个限制,所以如果k+1这个元素之前的和是小于0的,那么对于增大k+1这个元素从而去组成最大子序列是没有贡献的,所以可以把sum置0处理。

    本质上是DP问题。,只是要先求出sum。

    Solution 1 ()

    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int res = INT_MIN, sum = 0;
            for (int n : nums) {
            /*  if(sum < 0) sum = 0; 
                sum += A[i];
                res = max(res, sum); */
                sum = max(sum + n, n);
                res = max(res, sum);
            }
            return cur;
        }
    };

     Solution 2 (TLE)

    class Solution {
    public:
        int helper(vector<int> nums, int left, int right) {
            if(left >= right) return nums[left];
            int mid = left + (right - left)/2;
            int lmax = helper(nums, left, mid-1);
            int rmax = helper(nums, mid+1, right);
            int mmax = nums[mid], tmp = mmax;
            for(int i=mid-1; i>=left; --i) {
                tmp += nums[i];
                mmax = max(tmp, mmax);
            }
            tmp = mmax;
            for(int i=mid+1; i<=right; ++i) {
                tmp += nums[i];
                mmax = max(tmp, mmax);
            }
            return max(mmax, max(lmax, rmax));
        }
        int maxSubArray(vector<int>& nums) {
            if(nums.size() == 0) return 0;
            return helper(nums,0, nums.size()-1);
        }
    };
  • 相关阅读:
    MyBatis Generator 的使用
    Eclipse插件手动安装
    MyBatis中别名的设置
    MyBatis 插入时返回自增主键
    MyBatis 模糊查询
    MyBatis 多个查询条件的传递
    MyBatis 的Mapper中有小于号的处理
    spring mvc rest 方式
    jackson
    中兴阅读:你的移动阅读解决专家,助纸媒们一臂之力
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6816196.html
Copyright © 2020-2023  润新知