All problems
1149MediumArrayGreedySortingPrefix Sum

Ordering Entries to Keep the Totals Above Zero

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2587Rearrange Array to Maximize Prefix Score

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A list entries holds whole numbers, and they may be arranged in any order at all.

Once arranged, form the running totals: the first entry, then the first two added together, then the first three, and so on, giving one total per entry.

Return the largest number of those running totals that can be strictly above zero.

Examples

Example 1

Input
entries = [-6, -5, 4, 3, 2, 1]
Output
5

Taking the four positive entries first gives totals of 4, 7, 9 and 10. Adding -5 leaves 5, still above zero, and adding -6 drops it to -1, so five totals stay above zero.

Example 2

Input
entries = [5, -5, 5, -5]
Output
3

The two entries of 5 first give 5 and then 10, one -5 leaves 5, and the last brings the total exactly to zero, which does not count.

Example 3

Input
entries = [-1, -2, -3]
Output
0

Every entry is below zero, so whatever the order the very first total is already negative.

Constraints

  • 1 <= entries.length <= 10^5
  • -10^6 <= entries[i] <= 10^6

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def max_score(entries: list[int]) -> int:
Java
public int maxScore(int[] entries)
September 7
Apply