题目
https://leetcode-cn.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/
思路
考虑糖果最多和最少的两种情况。糖果最少时,恰好不能保证每天至少吃一颗。糖果最多时,最想吃的糖果前面的糖果已经占满了最喜欢的天之前的全部糖果容量。
一开始没有使用前缀和,提示超时。然后又没有将sum设置为long long int类型,提示数据溢出。
代码
class Solution {
public:
vector<bool> canEat(vector<int>& candiesCount, vector<vector<int>>& queries) {
vector<bool> answer(queries.size());
vector<long long int> sum(candiesCount.size());
sum[0]=candiesCount[0];
for(int i=1;i<candiesCount.size();i++){
sum[i]=sum[i-1]+candiesCount[i];
}
for(int i=0;i<queries.size();i++){
int type=queries[i][0],day=queries[i][1]+1,cap=queries[i][2];
if(sum[type]>=day&&(type==0||sum[type-1]/day<cap))
answer[i]=true;
}
return answer;
}
};
题解思路
题解代码
class Solution {
private:
using LL = long long;
public:
vector<bool> canEat(vector<int>& candiesCount, vector<vector<int>>& queries) {
int n = candiesCount.size();
// 前缀和
vector<LL> sum(n);
sum[0] = candiesCount[0];
for (int i = 1; i < n; ++i) {
sum[i] = sum[i - 1] + candiesCount[i];
}
vector<bool> ans;
for (const auto& q: queries) {
int favoriteType = q[0], favoriteDay = q[1], dailyCap = q[2];
LL x1 = favoriteDay + 1;
LL y1 = (LL)(favoriteDay + 1) * dailyCap;
LL x2 = (favoriteType == 0 ? 1 : sum[favoriteType - 1] + 1);
LL y2 = sum[favoriteType];
ans.push_back(!(x1 > y2 || y1 < x2));
}
return ans;
}
};