实现说明
前缀和快速回答区间求和可以归结为函数 rangeSum。
循环只出现在 for (const cents of dailyCents),它的每次迭代处理一个元素。
使用要点
- 每一步打印都带着自己的标签:
checkpoints:、days 1-3:、full week:。
常见问题
包管理器会看到什么?
一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 rangeSum。
主要签名是 const rangeSum = (from, to)
核心语句
const rangeSum = (from, to) => prefix[to + 1] - prefix[from];
const checkpoints = dailyCents.map((cents) => {
running += cents;
return running;
});
代码示例
const dailyCents = [1200, 850, 430, 2750, 190];
// Running total: one pass, each checkpoint carries everything seen so far
let running = 0;
const checkpoints = dailyCents.map((cents) => {
running += cents;
return running;
});
console.log('checkpoints:', checkpoints.join(', '));
// Prefix array starts at 0 so subtraction covers the first element too
const prefix = [0];
for (const cents of dailyCents) {
prefix.push(prefix[prefix.length - 1] + cents);
}
const rangeSum = (from, to) => prefix[to + 1] - prefix[from];
console.log('days 1-3:', rangeSum(1, 3));
console.log('full week:', rangeSum(0, dailyCents.length - 1));
const total = prefix[prefix.length - 1];
console.log('share by day 4:', Math.round((rangeSum(0, 3) / total) * 100) + '%');