<p>Given an integer array <code>arr</code>, partition the array into (contiguous) subarrays of length <strong>at most</strong> <code>k</code>. After partitioning, each subarray has their values changed to become the maximum value of that subarray.</p>

<p>Return <em>the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</em></p>

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

<pre>
<strong>Input:</strong> arr = [1,15,7,9,2,5,10], k = 3
<strong>Output:</strong> 84
<strong>Explanation:</strong> arr becomes [15,15,15,9,10,10,10]
</pre>

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

<pre>
<strong>Input:</strong> arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
<strong>Output:</strong> 83
</pre>

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

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

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

<ul>
	<li><code>1 &lt;= arr.length &lt;= 500</code></li>
	<li><code>0 &lt;= arr[i] &lt;= 10<sup>9</sup></code></li>
	<li><code>1 &lt;= k &lt;= arr.length</code></li>
</ul>

class Solution {
public:

    int segTree[2005];
    int dp[505][505];

    void build(int ind, int low, int high, vector<int> &arr){
        if(low == high){
            segTree[ind] = arr[low];
            return;
        } 

        int mid = low + ((high-low)>>1);
        build(2*ind+1, low, mid, arr);
        build(2*ind+2, mid+1, high, arr);

        segTree[ind] = max(segTree[2*ind+1], segTree[2*ind+2]);
    }

    int query(int ind, int low, int high, int l, int r){
        //completely inside
        if(low >= l && high <= r) return segTree[ind];
        //completely outside
        if(low > r || high < l) return INT_MIN;
        //partially inside
        int mid = low + ((high-low)>>1);
        int lmax = query(2*ind+1, low, mid, l, r);
        int rmax = query(2*ind+2, mid+1, high, l, r);
        return max(lmax, rmax);
    }

    int rec(int l, int r, vector<int> &arr, int k){
        int n = arr.size();
        if(l >= r) return arr[l];
        if(dp[l][r] != -1) return dp[l][r];

        int sum = (r-l+1 > k ? INT_MIN : query(0, 0, n-1, l, r)*(r-l+1));
        for(int i=l; i<r; i++){
            sum = max(sum, rec(l, i, arr, k)+rec(i+1, r, arr, k));
        }
        return dp[l][r] = sum;
    }    

    int maxSumAfterPartitioning(vector<int>& arr, int k) {
        int n = arr.size();
        memset(dp, -1, sizeof(dp));
        build(0, 0, n-1, arr);

        for(int l=n-1; l>=0; l--){
            for(int r=l; r<n; r++){
                int sum = (r-l+1 > k ? INT_MIN : query(0, 0, n-1, l, r)*(r-l+1));
                for(int i=l; i<r; i++){
                    sum = max(sum, dp[l][i]+dp[i+1][r]);
                } 
                dp[l][r] = sum;
            }
        }



        return dp[0][n-1];
    }
};
12100