[LeetCode] Rearrange Array to Maximize Prefix Score

2587. Rearrange Array to Maximize Prefix Score

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int maxScore(vector<int>& nums) {
sort(rbegin(nums), rend(nums));
long long sum = 0, res = 0;
for(int i = 0; i < nums.size(); i++) {
sum += nums[i];
if(sum > 0) res += 1;
else break;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/12/PS/LeetCode/rearrange-array-to-maximize-prefix-score/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.