<p>Given an integer array <code>nums</code> and an integer <code>k</code>, find three non-overlapping subarrays of length <code>k</code> with maximum sum and return them.</p>

<p>Return the result as a list of indices representing the starting position of each interval (<strong>0-indexed</strong>). If there are multiple answers, return the lexicographically smallest one.</p>

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

<pre>
<strong>Input:</strong> nums = [1,2,1,2,6,7,5,1], k = 2
<strong>Output:</strong> [0,3,5]
<strong>Explanation:</strong> Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
</pre>

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

<pre>
<strong>Input:</strong> nums = [1,2,1,2,1,2,1,2,1], k = 2
<strong>Output:</strong> [0,2,4]
</pre>

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

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;&nbsp;2<sup>16</sup></code></li>
	<li><code>1 &lt;= k &lt;= floor(nums.length / 3)</code></li>
</ul>

typedef long long int ll;

class Solution {
public:
    vector<int> maxSumOfThreeSubarrays(vector<int>& arr, int k) {

        ll n = arr.size();
        vector<int> ans( 3, 0);

        ll maxSum = 0;
        ll prefSum = 0;
        ll suffSum = 0;

        ll id = -1;

        vector<ll> ps( n, 0);
        vector<ll> ss( n, 0);

        vector<ll> fp( n, 0);
        vector<ll> bp( n, 0);

        for( ll i=0, tot=0; i<n; i++) {
            tot += arr[i];
            ps[i] = tot;
        }
        for( ll i=n-1, tot=0; i>=0; i--) {
            tot += arr[i];
            ss[i] = tot;
        }

        for( ll i=k-1, mx=0; i<n; i++) {
            ll curr = ps[i] - ((i-k>=0)?ps[i-k]:0);
            mx = max( mx, curr);
            fp[i] = max( fp[i], mx);
        }

        for( ll i=n-k, mx=0; i>=0; i--) {
            ll curr = ss[i] - ((i+k>=n)?0:ss[i+k]);
            mx = max( mx, curr);
            bp[i] = mx;
        }


        for( ll i=2*k-1, mx1=0, mx2=0; i<n-k; i++) {
            ll currPrefSum = fp[i-k];
            ll currSuffSum = bp[i+1];
            ll curr =  currPrefSum + ps[i] - ps[i-k] + currSuffSum;
            if(curr>maxSum) {
                maxSum = curr;
                prefSum = currPrefSum;
                suffSum = currSuffSum;
                id = i;
            }
        }

        for( ll i=0; i<n; i++) {
            ll curr = ss[i] - ss[i+k];
            if(curr==prefSum) {
                ans[0] = i;
                break;
            }
        }

        ans[1] = id-(k-1);

        for( ll i=id+1; i<=n-k; i++) {
            ll curr = ss[i] - ((i+k>=n)?0:ss[i+k]);
            if(curr==suffSum) {
                ans[2] = i;
                break;
            }
        }

        return ans;
    }
};
28008