zoukankan      html  css  js  c++  java
  • 154th LeetCode Weekly Contest

    A B D均比较简单。先说C题

    K-Concatenation Maximum Sum

    Given an integer array arr and an integer k, modify the array by repeating it k times.

    For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].

    Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.

    As the answer can be very large, return the answer modulo 10^9 + 7.

    Example 1:

    Input: arr = [1,2], k = 3
    Output: 9
    

    Example 2:

    Input: arr = [1,-2,1], k = 5
    Output: 2
    

    Example 3:

    Input: arr = [-1,-2], k = 7
    Output: 0
    

    Constraints:

    • 1 <= arr.length <= 10^5
    • 1 <= k <= 10^5
    • -10^4 <= arr[i] <= 10^4

    这里有个猜测,

    如果K=1,那么我只需要算这个数组的最大子数组和即可。

    如果K=2,那么我也只需要算这个数组的最大子数组和,只不过是多加了长度。

    如果K>2,那么不需要再讨论什么子数组了,实际上和K<=2类似。所以K>2以后的数组,如果和大于0,则全都要。

    class Solution {
    public:
        int kConcatenationMaxSum(vector<int>& arr, int k) {
            int sum1 = 0,sum2 = 0;
            int ant = 0;
            int sum3 = 0;
            int arrsize = arr.size();
            for(int i = 0;i<arrsize;i++){
                ant+=arr[i];
                sum3+=arr[i];
                sum1 = max(ant,sum1);
                if(ant<=0){
                    ant=0;
                }
            }
            ant = 0;
            for(int i = 0;i<arrsize*2;i++){
                ant+=arr[i%arrsize];
                sum2 = max(ant,sum2);
                if(ant<=0){
                    ant=0;
                }
            }
            if(k==1){
                return sum1;
            }
            cout<<sum3<<" "<<sum1<<" "<<sum2<<endl;
            if(sum3>0){
                for(int i=2;i<k;i++){
                    sum2 +=sum3;
                    sum2%=1000000007;
                }
            }
            return sum2;
        }
    };
  • 相关阅读:
    POJ3253Fence Repair(优先队列或单调队列)
    POJ3630Phone List(字典树)
    HDU1896Stones(优先队列)
    POJ3468 A Simple Problem with Integers(线段树延时标记)
    HDU3535AreYouBusy(分组背包)
    C++ 学习涨姿势汇总
    [C++] std::vector 使用
    Cocos2dx-3.2 引擎学习(四)之CCScheduler
    Cocos2dx-3.2 引擎学习(三)之AssetsManager
    Cocos2dx-3.2 引擎学习(二)之Director
  • 原文地址:https://www.cnblogs.com/yinghualuowu/p/11525205.html
Copyright © 2011-2022 走看看