← 中文资源

简体中文版本

前缀和快速回答区间求和

一遍累加得到每步的滚动合计,再建一个以 0 开头的前缀数组:任意 i..j 区间和变成一次减法,不必每次重新遍历原始数据。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

checkpoints: 1200, 2050, 2480, 5230, 5420
days 1-3: 4030
full week: 5420
share by day 4: 96%

实现说明

前缀和快速回答区间求和可以归结为函数 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) + '%');