0%

LeetCode - 1744 - 你能在你最喜欢的那天吃到你最喜欢的糖果吗?

题目

你能在你最喜欢的那天吃到你最喜欢的糖果吗?

题解

官方题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var canEat = function (candiesCount, queries) {
const n = candiesCount.length;

// 前缀和
const sum = new Array(n).fill(0);
sum[0] = candiesCount[0];
for (let i = 1; i < n; ++i) {
sum[i] = sum[i - 1] + candiesCount[i];
}

const q = queries.length;
const ans = new Array(q).fill(0);
for (let i = 0; i < q; ++i) {
const query = queries[i];
const favoriteType = query[0],
favoriteDay = query[1],
dailyCap = query[2];

const x1 = favoriteDay + 1;
const y1 = (favoriteDay + 1) * dailyCap;
const x2 = favoriteType == 0 ? 1 : sum[favoriteType - 1] + 1;
const y2 = sum[favoriteType];

ans[i] = !(x1 > y2 || y1 < x2);
}
return ans;
};

let candiesCount = [7, 4, 5, 3, 8],
queries = [
[0, 2, 2],
[4, 2, 4],
[2, 13, 1000000000],
];

console.log('canEat :>> ', canEat(candiesCount, queries));

收获

JS 的技巧

1
const ans = new Array(q).fill(0);

输出长度为 q 的数组,用 0 填充

了解了前缀和这个东西

[7, 4, 5, 3, 8]

用前缀和得到

[7,7+4 7+4+5,7+4+5+3,7+4+5+3+8]

然后拿到区间进行判断。