zoukankan      html  css  js  c++  java
  • LeetCode--Maximum Subarray

    Maximum Subarray

    Question

    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.
    m

    解题思想

    分治的思想,将数组分解为更小的两个子数组,最大序列要么再两边,要么再中间,只有这三种情况。

    具体实现

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    
    class Solution {
    public:
        // 利用分治的思想
        int maxSubArray(vector<int>& nums) {
            return maxSum3(nums, 0, nums.size() - 1);
        }
        int maxSum3(vector<int>& nums, int p, int q) {
            if (p > q) {
                return 0;
            }
            if (p == q) {
                return nums[p];
            }
            int lmax = 0;
            int lsum = 0;
            int m = (p + q) / 2;
            for (int i = m; i >= p; i--) {
                lsum += nums[i];
                lmax = max(lmax, lsum);
            }
            int rmax = 0;
            int rsum =0;
            for (int j = m + 1; j <= q; j++) {
                rsum += nums[j];
                rmax = max(rsum, rmax);
            }
            int total = lmax + rmax;
            if (total == 0)
                total = INT_MIN;
            return max(max(total, maxSum3(nums, p, m)), maxSum3(nums, m + 1, q));
    
        }
    };
    
  • 相关阅读:
    【C++标准库】C++11新特性
    使用线程池
    Halcon相机硬触发采集图片
    C#之线程同步
    多线程之异常处理
    java基础 Arrays
    java基础 static关键字
    java基础 String
    c# 更新web.config
    java 基础
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/6539558.html
Copyright © 2011-2022 走看看