题目描述
Problem: 6316. 重排数组以得到最大前缀分数
思路
目标是要找到前缀和为正数的最大个数,那么最先想到的就是让正数在前面,负数由小到大的在后面,就可以保证前面累加的和尽可能地大。
解题方法
1、先对
nums
进行降序排列
2、求前缀和,当前缀和大于0的时候,结果加一
复杂度
- 时间复杂度:
添加时间复杂度, 示例: O ( n l o g n ) O(nlogn) O(nlogn)
- 空间复杂度:
添加空间复杂度, 示例: O ( 1 ) O(1) O(1)
Code
class Solution {
public:
static bool cmp(int a, int b) {
return a > b; // 前面大于后面,降序排列
}
int maxScore(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end(), cmp);
long long pfSum = 0;
int res = 0;
for(int i = 0; i < n; i++) {
pfSum += nums[i];
if(pfSum > 0) res++;
}
return res;
}
};