难度:中等。
标签:贪心,数组,排序。
对costs进行排序,从小到大买。
正确解法:
class Solution {
public:
int maxIceCream(vector<int>& costs, int coins) {
int n = costs.size();
sort(costs.begin(), costs.end());
int ans = 0;
for(int i = 0; i < n; ++i){
if(costs[i] <= coins){
ans++;
coins -= costs[i];
}
}
return ans;
}
};
结果: