pls solve the problem with c++,optimize code man
Created on: June 25, 2026
Answered using GPT-5.5 Thinking by Chat01
Created on: June 25, 2026
Answered using GPT-5.5 Thinking by Chat01
pls solve the problem with c++,optimize code man
Use this as the function body. Keep the exact function name from your editor if it differs.
cpp#include <bits/stdc++.h> using namespace std; int calculateMaximumConsecutiveValueSum(int k, vector<vector<int>> segments) { using ll = long long; using i128 = __int128_t; const ll MOD = 1000000007LL; int n = segments.size(); if (n == 0) return 0; vector<array<ll, 3>> a; for (auto &v : segments) { a.push_back({(ll)v[0], (ll)v[1], (ll)v[2]}); // left, right, money per bag } sort(a.begin(), a.end()); vector<ll> L(n), R(n), C(n); vector<i128> pref(n + 1, 0); for (int i = 0; i < n; i++) { L[i] = a[i][0]; R[i] = a[i][1]; C[i] = a[i][2]; pref[i + 1] = pref[i] + (i128)(R[i] - L[i] + 1) * C[i]; } auto getSum = [&](ll ql, ll qr) -> i128 { if (ql > qr) return 0; int first = lower_bound(R.begin(), R.end(), ql) - R.begin(); if (first == n) return 0; int last = upper_bound(L.begin(), L.end(), qr) - L.begin() - 1; if (last < first) return 0; i128 ans = pref[last + 1] - pref[first]; if (ql > L[first]) { ans -= (i128)(ql - L[first]) * C[first]; } if (qr < R[last]) { ans -= (i128)(R[last] - qr) * C[last]; } return ans; }; ll K = k; i128 best = 0; // Bag numbers start from 1. best = max(best, getSum(1, K)); for (int i = 0; i < n; i++) { // Case 1: chosen k bags start at the beginning of a segment. best = max(best, getSum(L[i], L[i] + K - 1)); // Case 2: chosen k bags end at the end of a segment. ll start = R[i] - K + 1; if (start < 1) start = 1; best = max(best, getSum(start, start + K - 1)); } return (int)(best % MOD); }
This does not create an array for all bags. It only works on the given ranges.
Time complexity: O(n log n)
Space complexity: O(n)