#2587

Rearrange Array to Maximize Prefix Score

Medium
ArrayGreedySortingPrefix SumGreedySortingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

To maximize the number of positive prefix sums, we should sort the array in descending order. This way, we ensure that larger numbers contribute positively to the prefix sums early on, maximizing the count of positive values.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array nums in descending order.
  2. 2Step 2: Initialize prefix sum and score to 0.
  3. 3Step 3: Iterate through the sorted array, updating the prefix sum and counting positive values.
solution.py11 lines
1# Full working Python code
2
3def maxPrefixScore(nums):
4    nums.sort(reverse=True)
5    prefix_sum = 0
6    score = 0
7    for num in nums:
8        prefix_sum += num
9        if prefix_sum > 0:
10            score += 1
11    return score

Complexity note: The time complexity is dominated by the sorting step, which is O(n log n). The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Sorting the array in descending order maximizes the positive contributions to the prefix sums.
  • 2The prefix sum must be tracked to count how many positive values are generated.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.