Rearrange Array to Maximize Prefix Score - Problem
Rearrange Array to Maximize Prefix Score

You're given an array of integers and need to find the optimal arrangement that maximizes the number of positive prefix sums.

๐ŸŽฏ The Challenge: Given a 0-indexed integer array nums, you can rearrange its elements in any order. After rearrangement, create a prefix sum array where prefix[i] represents the sum of all elements from index 0 to i.

Your score is the count of positive values in this prefix array. Return the maximum possible score.

Example: For [2, -1, 0, 1, -3, 3, -3], one optimal arrangement is [3, 2, 1, 0, -1, -3, -3] giving prefix sums [3, 5, 6, 6, 5, 2, -1] with 6 positive values.

Input & Output

example_1.py โ€” Basic Case
$ Input: [2, -1, 0, 1, -3, 3, -3]
โ€บ Output: 6
๐Ÿ’ก Note: Optimal arrangement is [3, 2, 1, 0, -1, -3, -3] giving prefix sums [3, 5, 6, 6, 5, 2, -1]. The first 6 values are positive.
example_2.py โ€” All Negative
$ Input: [-2, -3, 0]
โ€บ Output: 0
๐Ÿ’ก Note: Best arrangement is [0, -2, -3] with prefix sums [0, -2, -5]. No positive values, so score is 0.
example_3.py โ€” All Positive
$ Input: [1, 3, 2, 1]
โ€บ Output: 4
๐Ÿ’ก Note: Any arrangement works since all numbers are positive. Prefix sums will always all be positive, giving maximum score of 4.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -106 โ‰ค nums[i] โ‰ค 106
  • Important: Use long/long long for prefix sum calculations to avoid integer overflow

Visualization

Tap to expand
Bank Account Balance Over TimeTransactions: [+$3000, +$2000, +$1000, $0, -$1000, -$3000, -$3000]$0+$3k-$3k6 Months with Positive BalanceMonth 1Month 2Month 3Month 4Month 5Month 6Month 7+$3000+$2000+$1000$0-$1000-$3000-$3000
Understanding the Visualization
1
Collect All Transactions
You have various income (+) and expense (-) items to schedule
2
Schedule Largest Income First
Arrange to receive your biggest payments early to build up buffer
3
Add Remaining in Descending Order
Continue with smaller income, then zero, then expenses smallest to largest
4
Track Positive Months
Count how many months your running balance stays positive
Key Takeaway
๐ŸŽฏ Key Insight: Greedy scheduling works! Arrange positive cash flows first (largest to smallest) to maximize the number of profitable periods.
Asked in
Google 42 Meta 35 Amazon 28 Microsoft 22
28.5K Views
Medium-High Frequency
~15 min Avg. Time
847 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