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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code