Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Little Girl and Maximum Sum Editorial #5042

Merged
merged 14 commits into from
Jan 15, 2025
2 changes: 1 addition & 1 deletion content/3_Silver/More_Prefix_Sums.problems.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"isStarred": false,
"tags": ["Difference Array"],
"solutionMetadata": {
"kind": "none"
"kind": "internal"
}
}
],
Expand Down
81 changes: 81 additions & 0 deletions solutions/silver/cf-276C.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
id: cf-276C
source: CF
title: Little Girl and Maximum Sum
author: Rameez Parwez
---

## Explanation

We can calculate the contribution of each index in the range query using a difference array technique.

To maximize the sum, sort both the array and frequency array in descending order
and pair the elements of the array with their respective frequencies.

## Implementation

**Time Complexity:** $ \mathcal{O} (N \log N)$

<LanguageSection>
<CPPSection>

```cpp
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
int n, q;
std::cin >> n >> q;
std::vector<int> arr(n);

for (int &x : arr) { std::cin >> x; }

std::vector<int> freq(n + 1);
for (int i = 0; i < q; i++) {
int l, r;
std::cin >> l >> r;
l--;
freq[l] += 1;
freq[r] -= 1;
}

for (int i = 1; i <= n; i++) { freq[i] += freq[i - 1]; }

std::sort(std::rbegin(freq), std::rend(freq));
std::sort(std::rbegin(arr), std::rend(arr));

long long res = 0;
for (int i = 0; i < n; i++) { res += 1LL * freq[i] * arr[i]; }
std::cout << res << endl;
}
```

</CPPSection>
<PySection>

```py
n, q = map(int, input().split())
arr = list(map(int, input().split()))

freq = [0] * (n + 1)
for _ in range(q):
l, r = map(int, input().split())
freq[l - 1] += 1
freq[r] -= 1

for i in range(1, n + 1):
freq[i] += freq[i - 1]

freq.sort(reverse=True)
arr.sort(reverse=True)

res = 0
for i in range(n):
res += freq[i] * arr[i]

print(res)
```

</PySection>
</LanguageSection>
Loading