Skip to content

2587. Rearrange Array to Maximize Prefix Score 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maxScore(vector<int>& nums) {
    long prefix = 0;

    ranges::sort(nums, greater<>());

    for (int i = 0; i < nums.size(); ++i) {
      prefix += nums[i];
      if (prefix <= 0)
        return i;
    }

    return nums.size();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int maxScore(int[] nums) {
    long prefix = 0;

    nums = Arrays.stream(nums)
               .boxed()
               .sorted(Collections.reverseOrder())
               .mapToInt(Integer::intValue)
               .toArray();

    for (int i = 0; i < nums.length; ++i) {
      prefix += nums[i];
      if (prefix <= 0)
        return i;
    }

    return nums.length;
  }
}
1
2
3
4
class Solution:
  def maxScore(self, nums: list[int]) -> int:
    return sum(num > 0
               for num in itertools.accumulate(sorted(nums, reverse=True)))