Rearrange Array to Maximize Prefix Score - Problem

You are given a 0-indexed integer array nums. You can rearrange the elements of nums to any order (including the given order).

Let prefix be the array containing the prefix sums of nums after rearranging it. In other words, prefix[i] is the sum of the elements from 0 to i in nums after rearranging it. The score of nums is the number of positive integers in the array prefix.

Return the maximum score you can achieve.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,-1,-3,4]
Output: 4
💡 Note: After sorting to [4,2,-1,-3], prefix sums are [4,6,5,2]. All 4 are positive, so score is 4.
Example 2 — Mixed Values
$ Input: nums = [-1,-2,-3]
Output: 0
💡 Note: All numbers are negative. After sorting to [-1,-2,-3], prefix sums are [-1,-3,-6]. None are positive, so score is 0.
Example 3 — Single Element
$ Input: nums = [5]
Output: 1
💡 Note: Single positive element gives prefix sum [5], which is positive. Score is 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Rearrange Array to Maximize Prefix ScoreOriginal: [2, -1, -3, 4]2-1-342✓1✓-2✗2✓Score: 3 positive sumsRearrange OptimallyOptimal: [4, 2, -1, -3]42-1-34✓6✓5✓2✓Score: 4 positive sumsMaximumScore: 4Strategy: Sort largest first → maximize positive prefix sums
Understanding the Visualization
1
Input
Array [2,-1,-3,4] with original prefix sums
2
Rearrange
Sort descending to maximize positive prefix sums
3
Output
Count of positive prefix sums after optimal arrangement
Key Takeaway
🎯 Key Insight: Greedy sorting places largest elements first to keep running sums positive as long as possible
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen