You are given an integer array nums of length n and an integer k.
You must select exactlykdistinct non-empty subarrays nums[l..r] of nums. Subarrays may overlap, but the exact same subarray (same l and r) cannot be chosen more than once.
The value of a subarray nums[l..r] is defined as: max(nums[l..r]) - min(nums[l..r]).
The total value is the sum of the values of all chosen subarrays.
Return the maximum possible total value you can achieve.
longlonghelper1(vector<int>& A, longlong x){ longlong n = A.size(), l = 0, res = 0; deque<int> ma, mi; for (int r = 0; r < n; ++r) { while (!ma.empty() and A[ma.back()] <= A[r]) ma.pop_back(); ma.push_back(r); while (!mi.empty() and A[mi.back()] >= A[r]) mi.pop_back(); mi.push_back(r); while (!ma.empty() and !mi.empty() && A[ma.front()] - A[mi.front()] >= x) { if (ma.front() == l) ma.pop_front(); if (mi.front() == l) mi.pop_front(); ++l; } res += l; } return res; }
longlonghelper2(vector<int>& a, int T){ int n = a.size(), l = 0; deque<int> ma, mi; Agg Amax, Amin; longlong res = 0; for (int r = 0; r < n; ++r) { Amax.push(a[r], true); Amin.push(a[r], false); while (!ma.empty() and a[ma.back()] <= a[r]) ma.pop_back(); ma.push_back(r); while (!mi.empty() and a[mi.back()] >= a[r]) mi.pop_back(); mi.push_back(r); while (!ma.empty() and !mi.empty() && a[ma.front()] - a[mi.front()] > T) { if (ma.front() == l) ma.pop_front(); if (mi.front() == l) mi.pop_front(); ++l; } int L = l; longlong X = (L <= r) ? (r - L + 1) : 0; longlong sumMaxLeft = Amax.sumAll - Amax.sumLast(X); longlong sumMinLeft = Amin.sumAll - Amin.sumLast(X); res += (sumMaxLeft - sumMinLeft - 1ll * T * L); } return res; }
public: longlongmaxTotalValue(vector<int>& nums, int k){ longlong l = 0, r = *max_element(nums.begin(), nums.end()) - *min_element(nums.begin(), nums.end()), res = 0; while (l <= r) { longlong m = l + (r - l) / 2; bool ok = helper1(nums, m) >= k; if(ok) { l = m + 1; res = m; } else r = m - 1; } returnhelper2(nums,res) + res * k; } };