zoukankan      html  css  js  c++  java
  • [模板] 循环数组的最大子段和

    数组的最大子段和

    不断保留当前段的最大值, 时间复杂度O(n)

    初始段为首位元素

    若该段加下一元素比下一元素大

    则段加和有意义且可累积更大和

    若非则断段, 段从下一元素开始从新累计

    循环数组则要考虑首尾相接是和最大的情况

    若首尾相接 则必定有 中间段之和最负

    求出最负段的和 用总元素和减去最负段的和

    即为该情况的解

    具体可用所有元素取负后再求最大子段和

    该和求负即为最负子段和

    //#pragma GCC optimize(2)
    #include <cstdio>
    #include <iostream>
    #include <cstdlib>
    #include <cmath>
    #include <cctype>
    #include <string>
    #include <cstring>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <set>
    #include <map>
    #include <ctime>
    #include <vector>
    #include <fstream>
    #include <list>
    #include <iomanip>
    #include <numeric>
    using namespace std;
    #define int long long
     
    const int MAXN = 1e6 + 10;
    
    int n, arr[MAXN], brr[MAXN], sum = 0;
    
    signed main()
    {
        //ios::sync_with_stdio(false);
     
        //cin.tie(0);     cout.tie(0);
        
        cin>>n;
    
        for(int i = 0; i < n; i++)
        {
            cin>>arr[i];
            brr[i] = -arr[i];
            sum +=  arr[i];
        }
        
        int t = arr[0], rt = arr[0], ans;
    
        for(int i = 1; i < n; i++)
        {
            if(t + arr[i] < arr[i])
                t = arr[i];
            else
                t += arr[i];
    
            rt = max(rt, t);
        }
        
        ans = rt;
    
        t = brr[0], rt = brr[0];
    
        for(int i = 1; i < n; i++)
        {
            if(t + brr[i] < brr[i])
                t = brr[i];
            else
                t += brr[i];
    
            rt = max(rt, t);
        } 
     
        ans = max(ans, sum + rt);
    
        cout<<ans<<endl;
    
        return 0;
    }
  • 相关阅读:
    [LeetCode]题解(python):119-Pascal's Triangle II
    [LeetCode]题解(python):118-Pascal's Triangle
    [LeetCode]题解(python):117-Populating Next Right Pointers in Each Node II
    寒假自学进度8
    寒假自学进度7
    寒假自学进度6
    寒假自学5
    寒假自学学习4
    寒假自学进度3
    寒假自学进度2
  • 原文地址:https://www.cnblogs.com/zeolim/p/9776923.html
Copyright © 2011-2022 走看看