【问题标题】:Intuition behind calculating the prefix and suffix sums计算前缀和后缀和的直觉
【发布时间】:2021-05-25 06:37:52
【问题描述】:

我正在解决一个LeetCode question:将所有球移动到每个盒子的最小操作数。

您有n 框。给定一个长度为n 的二进制字符串框,其中boxes[i] 如果ith 框为空,则为'0',如果它包含一个球,则为'1'。在一次操作中,您可以将一个球从一个盒子移动到一个相邻的盒子。返回大小为n 的数组答案,其中answer[i] 是将所有球移动到ith 框所需的最小操作数。对于输入boxes = "001011",输出为:[11,8,5,4,3,4]

O(n^2) 中执行此操作是微不足道的。我只能这样解决。我正在尝试了解this O(n) 解决方案,但很难:

class Solution {
    public int[] minOperations(String boxes) {
        int n = boxes.length();

        int[] left = new int[n];
        int[] right = new int[n];
        int[] ans = new int[n];

        int count = boxes.charAt(0) - '0';
        for(int i = 1 ; i < n ; i++){
            left[i] = left[i - 1] + count;
            count += boxes.charAt(i) - '0';
            // System.out.println("i: "+i+" left[i]: "+left[i]+" left[i-1] : "+left[i-1]+" count: " + count);
        }

        count = boxes.charAt(n - 1) - '0';
        for(int i = n - 2 ; i >=0 ; i--){
            right[i] = right[i + 1] + count;
            count += boxes.charAt(i) - '0';
            // System.out.println("i: "+i+" right[i]: "+right[i]+" right[i+1] : "+right[i+1]+" count: " + count);
        }
        
        for(int i = 0 ; i < n ; i++) {
            ans[i] = left[i] + right[i];
        }

        return ans;
    }
}

有人能详细说明一下背后的逻辑吗:

left[i] = left[i - 1] + count;
count += boxes.charAt(i) - '0';

我知道每当遇到球时我们都会增加count,但是left[i] = left[i - 1] + count; 如何帮助我们计算到目前为止将左侧的所有球移动到i 所需的操作数(反之亦然,以防万一right)?

谢谢!

【问题讨论】:

  • 基本思想是从索引i 移动到索引i+1 会增加每个球向左的操作次数。所以如果左边有count个球,那么操作总数增加count

标签: java algorithm prefix-sum


【解决方案1】:

left[i] 视为将所有球从 0 开始移动到第 i 个索引的成本。

所以,

left[i] = 
  left[i - 1]  (cost to move all 1's to (i - 1) the index) 
  + count      (this is the total number of 1's which will all need to be moved to the ith index so, its cost is count)

【讨论】:

    【解决方案2】:

    This comment 来自 @dunkypie 帮助:

    “我终于用 DP 建立了对这个问题的直觉。就是这样。当我们说计算将一个盒子左边的所有球移动到那个 bax 的操作数时,假设我们在第 i 个位置(或盒子)。这由两部分组成,首先 dp[i - 1] 将为我们提供将所有球移动到第 (i - 1) 个位置的操作次数,现在我们将所有球移动到 (第 i - 1) 个位置在第 (i - 1) 个位置(或盒子)。然后下一部分涉及将所有这些球在第 (i - 1) 个位置移动到第 i 个位置。还要注意移动 a 1个位置的单球是1。所以递归关系变为:

    dp[i] = dp[i - 1] + (1 * balls) 其中 1 是移动单个球的成本。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 2015-07-29
      相关资源
      最近更新 更多