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 Score INPUT Original Array nums[] 2 i=0 -1 i=1 -3 i=2 4 i=3 Goal: Rearrange array to maximize count of positive prefix sums Input Values nums = [2,-1,-3,4] Length: 4 Sum: 2 ALGORITHM STEPS 1 Sort Descending Largest values first 4 2 -1 -3 2 Calculate Prefix Running sum at each i 3 Build Prefix Array prefix[i] = sum(0..i) i=0: 4 [OK] i=1: 4+2=6 [OK] i=2: 6-1=5 [OK] i=3: 5-3=2 [OK] 4 Count Positives prefix = [4,6,5,2] All 4 are positive! FINAL RESULT Sorted Array (Optimal Order) 4 2 -1 -3 Prefix Sum Array 4 6 5 2 All values are positive! OUTPUT 4 Maximum Score = 4 (All 4 prefixes positive) Key Insight: By sorting in descending order, we ensure the largest positive values are added first to the prefix sum. This keeps the running sum positive for as long as possible, maximizing the score. Time Complexity: O(n log n) for sorting | Space Complexity: O(1) or O(n) depending on sort TutorialsPoint - Rearrange Array to Maximize Prefix Score | Greedy Sorting Approach
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