Can You Eat Your Favorite Candy on Your Favorite Day? LeetCode solution in Java

1
class Solution {
2
// T = O(n) S=O(n)
3
public boolean[] canEat(int[] candiesCount, int[][] queries) {
4
// calculate prefix sum
5
long[] prefix = new long[candiesCount.length + 1];
6
boolean[] res = new boolean[queries.length];
7
prefix[0] = 0;
8

9
for (int i = 1; i < prefix.length; i++) prefix[i] = prefix[i - 1] + candiesCount[i - 1];
10

11
for (int i = 0; i < res.length; i++) {
12
int type = queries[i][0];
13
int day = queries[i][1];
14
int cap = queries[i][2];
15

16
// max and min day required to eat
17
// if we eat one candy per day including type candy (prefix[type+1]). we decrement by 1 since
18
// we need atleast one candy of type
19
long maxDay = prefix[type + 1] - 1;
20
// if we eat upto capacity each day upto previous candy
21
long minDay = prefix[type] / cap;
22

23
// check if query day is within the limits (minDay and maxDay inclusive)
24
res[i] = (minDay <= day && day <= maxDay);
25
}
26

27
return res;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0