<p>Given an integer array <code>arr</code> and an integer <code>k</code>, modify the array by repeating it <code>k</code> times.</p>

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

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

<p>As the answer can be very large, return the answer <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> arr = [1,2], k = 3
<strong>Output:</strong> 9
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> arr = [1,-2,1], k = 5
<strong>Output:</strong> 2
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> arr = [-1,-2], k = 7
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= arr.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= arr[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    int max_sum(vector<int> a) {
        int mn_pf = 0, pf = 0, res = 0;
        for (int i: a) {
            pf += i;
            res = max(res, pf - mn_pf);
            mn_pf = min(mn_pf, pf);
        }        
        return res;
    }

    int kConcatenationMaxSum(vector<int>& arr, int k) {
        long long res = max_sum(arr);
        if (k == 1) return res;

        int sum = 0;
        for (int i: arr) {
            sum += i;
        }

        if (sum >= 0) {
            int mx_pf = -1e9, mx_sf = -1e9, pf = 0, sf = 0;
            for (int i = 0; i < arr.size(); i++) {
                pf += arr[i];
                sf += arr[arr.size()-i-1];
                mx_pf = max(mx_pf, pf);
                mx_sf = max(mx_sf, sf);
            }
            res = max(res, mx_pf + mx_sf + (long long)sum*(k-2));
        } else {
            vector<int> a = arr;
            for (int i: arr) {
                a.push_back(i);
            }
            res = max(res, (long long)max_sum(a));
        }
        return res % 1000000007;
    }
};
46300