#1589
Maximum Sum Obtained of Any Permutation
MediumArrayGreedySortingPrefix SumGreedySortingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach focuses on understanding the frequency of each index in the requests. By sorting `nums` in descending order and assigning larger values to indices that are accessed more frequently, we maximize the total sum efficiently.
⚙️
Algorithm
5 steps- 1Step 1: Create a frequency array to count how many times each index is included in the requests.
- 2Step 2: For each request, increment the frequency for the start index and decrement after the end index to mark the range.
- 3Step 3: Compute the prefix sum of the frequency array to get the actual counts for each index.
- 4Step 4: Sort the frequency array and the `nums` array in descending order.
- 5Step 5: Multiply the sorted values together and sum them up to get the maximum total sum.
solution.py19 lines
1# Full working Python code
2import numpy as np
3
4MOD = 10**9 + 7
5
6def maxSum(nums, requests):
7 n = len(nums)
8 freq = [0] * (n + 1)
9 for start, end in requests:
10 freq[start] += 1
11 if end + 1 < n:
12 freq[end + 1] -= 1
13 for i in range(1, n):
14 freq[i] += freq[i - 1]
15 freq = freq[:-1] # Remove the last extra element
16 nums.sort(reverse=True)
17 freq.sort(reverse=True)
18 max_sum = sum(f * n for f, n in zip(freq, nums)) % MOD
19 return max_sumℹ
Complexity note: The time complexity is O(n log n) due to the sorting of the frequency and nums arrays. The space complexity is O(n) for the frequency array.
- 1Higher frequency indices should be paired with larger values to maximize the sum.
- 2Using a frequency array allows us to efficiently calculate the contribution of each index.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.