Simplest 1-pass solution, O(1) space, very easy to understand
\n// Runtime: O(N)\n// Space: O(1) excluding inputs\n// Very simple algo.\n// The best subarray of the expanded arr must be one of the following patterns:\n// 1
```\n// Runtime: O(N)\n// Space: O(1) excluding inputs\n// Very simple algo.\n// The best subarray of the expanded arr must be one of the following patterns:\n// 1) [...S2][...]...[...][S1...] for K >= 2\n// 2) [...S2][...]...[...] for K >= 2\n// 3) [...maxsum...] for K==1\n// where :\n//  each [] denotes arr and \n//  maxsum is the max sum of a sequence within arr\n//  S2 is the best sum of a sequence ending at the last index\n//  S1 is the best sum of a sequence starting at 0\n// So we just calculate the max sum of each pattern and viola!\nclass Solution {\npublic:\n    inline static constexpr int mod = 1e9+7;\n    \n    int kConcatenationMaxSum(vector<int>& arr, int k) {\n        int64_t sum1 = 0;\n        int64_t sum2 = 0;\n        int64_t sum1best = 0; // S1\n        int64_t sum2best = 0; // S2\n        int64_t cursum = 0;\n        int64_t maxsum = 0;\n        for (int i=0;i<arr.size();i++){\n            sum1 += arr[i];\n            sum2 += arr[arr.size()-1-i];\n            sum1best = max(sum1best, sum1);\n            sum2best = max(sum2best, sum2);\n            cursum = max((int64_t)0, cursum + arr[i]);\n            maxsum = max(maxsum, cursum);\n        }\n         \n        int64_t ans = max(maxsum, sum2best  + (k-1)*sum1);\n        if (k >= 2)\n            ans = max(ans, sum1best + sum2best  + (k-2)*max((int64_t)0,sum1));\n        return ans % mod;\n    }\n};\n```
[]