题目:
There is a special kind of apple tree that grows apples every day for n
days. On the ith
day, the tree grows apples[i]
apples that will rot after days[i]
days, that is on day i + days[i]
the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0
and days[i] == 0
.
You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n
days.
Given two integer arrays days
and apples
of length n
, return the maximum number of apples you can eat.
Example 1:
Input: apples = [1,2,3,5,2], days = [3,2,1,4,2] Output: 7 Explanation: You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day.
Example 2:
Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2] Output: 5 Explanation: You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day.
Constraints:
apples.length == n
days.length == n
1 <= n <= 2 * 10^4
0 <= apples[i], days[i] <= 2 * 10^4
days[i] = 0
if and only ifapples[i] = 0
.
思路:
首先这题数据量不大,只有10的4次,所以完全能够接受遍历n。我用了哈希表存苹果要过期的时间和数量,记录要过期的最大时间。然后用三个int,分别是count,记录答案,最大能吃多少;cur,如果每天不吃的话现在手上的苹果量;act,如果当前能吃并且吃了一个的情况下,手上真实的苹果量。然后从0开始循环到找到的最大天数,每天就是往cur里加苹果和减苹果,如果当前手里大于等于1,则就吃一个,在count上记录。这样看上去是不是好像不用act?但是如果apples=[1],days=[2],那么没有act的情况下答案是2,这其实是最后一个test case,因为我们第二天吃的那个苹果已经在第一天被吃掉了,不可能再被吃一下,这就意味着我们需要一个act来记录真实的苹果情况。但是显然,我们不能直接用cur来记录,否则前面天天被吃,后面删减苹果的时候删减的是原本成熟时的数量,会导致cur变成负数。因此我们采用act,并且在每次更新cur的时候,把cur复制给act来更新act,这样既能记录理论上苹果数量,又可以知道真实的苹果数量,这一天能不能吃到。
代码:
class Solution {
public:
int eatenApples(vector<int>& apples, vector<int>& days) {
int time=0;
unordered_map<int,int> out;
for(int i=0;i<apples.size();i++)
{
int temp=i+days[i]+1;
out[temp]+=apples[i];
time = max(time, temp);
}
int count = 0, cur = 0,act=0;
for (int i = 0; i <= time; i++)
{
if (out.count(i))
{
cur -= out[i];
act = cur;
}
if (i - 1 < apples.size())
{
cur += apples[i - 1];
act = cur;
}
if (act >= 1)
{
count += 1;
act--;
}
}
return count;
}
};