#2587

Rearrange Array to Maximize Prefix Score

specialist · 990 · lc medium +32 · verified · 42.5% accepted · 309 likes · top 24%

Description

You are given a 0-indexed integer array nums that you may rearrange in any order. Define prefix as the prefix-sum array after rearranging, where prefix[i] is the sum of elements from index 0 to i. The score of nums is the number of positive values in prefix. Return the maximum achievable score.

Example 1:

Input: nums = [2,-1,0,1,-3,3,-3]
Output: 6
Explanation: We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].
prefix = [2,5,6,5,2,2,-1], so the score is 6.
It can be shown that 6 is the maximum score we can obtain.

Example 2:

Input: nums = [-2,-3,0]
Output: 0
Explanation: Any rearrangement of the array will result in a score of 0.

Code

1
2
3