leetcode - 1769. Minimum Number of Operations to Move All Balls to Each Box

Description

You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.

In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.

Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.

Each answer[i] is calculated considering the initial state of the boxes.

Example 1:

复制代码
Input: boxes = "110"
Output: [1,1,3]
Explanation: The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.

Example 2:

复制代码
Input: boxes = "001011"
Output: [11,8,5,4,3,4]

Constraints:

复制代码
n == boxes.length
1 <= n <= 2000
boxes[i] is either '0' or '1'.

Solution

Brute Force

Iterate once to get all the indexes of balls, then iterate again to calculate: ∑ ∣ ball_index − i ∣ \sum |\text{ball\_index} - i| ∑∣ball_index−i∣

Time complexity: o ( n 2 ) o(n^2) o(n2)

Space complexity: o ( n ) o(n) o(n)

Prefix sum

Like 238. Product of Array Except Self, we can have left_cnt to denote the number of balls at the left of the current index, when moving one step forward, we have an extra left_cnt cost to move all the balls. We could do the same for right_cnt, and the final result would be left_cost + right_cost.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( 1 ) o(1) o(1)

Code

Brute Force

python3 复制代码
class Solution:
    def minOperations(self, boxes: str) -> List[int]:
        ball_indexes = []
        for i in range(len(boxes)):
            if boxes[i] == '1':
                ball_indexes.append(i)
        res = []
        for i in range(len(boxes)):
            cur_res = 0
            for each_ball_index in ball_indexes:
                cur_res += abs(each_ball_index - i)
            res.append(cur_res)
        return res

Prefix sum

python3 复制代码
class Solution:
    def minOperations(self, boxes: str) -> List[int]:
        res = [0] * len(boxes)
        left_cnt = 0
        left_cost = 0
        for i in range(1, len(boxes)):
            if boxes[i - 1] == '1':
                left_cnt += 1
            left_cost += left_cnt
            res[i] += left_cost
        right_cnt = 0
        right_cost = 0
        for i in range(len(boxes) - 2, -1, -1):
            if boxes[i + 1] == '1':
                right_cnt += 1
            right_cost += right_cnt
            res[i] += right_cost
        return res
相关推荐
呃呃本5 分钟前
算法题(栈)
算法
通信小呆呆11 分钟前
基于 ADMM-MFOCUSS 的捷变频雷达扩展目标稀疏重构原理
算法·重构·信息与通信·信号处理·雷达
橙淮21 分钟前
Java数组与链表:特性对比与应用场景
数据结构·算法
炽烈小老头24 分钟前
【每天学习一点算法 2026/05/15】被围绕的区域
学习·算法·深度优先
芜湖xin25 分钟前
【题解-洛谷】P1012 [NOIP 1998 提高组] 拼数
算法·贪心
xiaoxiaoxiaolll1 小时前
金属结构疲劳寿命预测与健康监测技术
人工智能·算法·机器学习
故事和你911 小时前
洛谷-【图论2-1】树4
开发语言·数据结构·c++·算法·动态规划·图论
故事和你911 小时前
洛谷-【图论2-1】树1
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
敲代码的嘎仔2 小时前
力扣高频SQL基础50题详解
开发语言·数据库·笔记·sql·算法·leetcode·后端开发
小虎牙0072 小时前
面试被问复杂度总懵?这篇指南帮你彻底搞清
算法