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.
Input: nums =[2,-1,0,1,-3,3,-3]Output: 6Explanation: 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 is6.It can be shown that 6is the maximum score we can obtain.
To maximize the number of positive prefix sums, we should add the largest numbers first. Sorting in descending order ensures the prefix sum stays positive as long as possible.
classSolution {
public:int maxScore(vector<int>& nums) {
sort(nums.rbegin(), nums.rend());
longlong sum =0;
int ans =0;
for (int x : nums) {
sum += x;
if (sum >0) ++ans;
elsebreak;
}
return ans;
}
};
import java.util.*;
classSolution {
publicintmaxScore(int[] nums) {
Arrays.sort(nums);
int n = nums.length, ans = 0;
long sum = 0;
for (int i = n-1; i >= 0; --i) {
sum += nums[i];
if (sum > 0) ++ans;
elsebreak;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funmaxScore(nums: IntArray): Int {
nums.sortDescending()
var sum = 0Lvar ans = 0for (x in nums) {
sum += x
if (sum > 0) ans++elsebreak }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaxScore(self, nums: list[int]) -> int:
nums.sort(reverse=True)
ans = s =0for x in nums:
s += x
if s >0:
ans +=1else:
breakreturn ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmax_score(mut nums: Vec<i32>) -> i32 {
nums.sort_by(|a, b| b.cmp(a));
letmut sum =0i64;
letmut ans =0;
for x in nums {
sum += x asi64;
if sum >0 { ans +=1; } else { break; }
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
maxScore(nums: number[]):number {
nums.sort((a, b) =>b-a);
letans=0, sum=0;
for (constxofnums) {
sum+=x;
if (sum>0) ++ans;
elsebreak;
}
returnans;
}
}