Skip to main content

1769.js

/** ------------------------------------------------------------------------------
*
* 1769. Minimum Number of Operations to Move All Balls to Each Box
* Topics: Array, Prefix Sum
* https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/?envType=daily-question&envId=2025-01-06
*
------------------------------------------------------------------------------ */
/**
* @param {string} boxes
* @return {number[]}
*/
var minOperations = function (boxes) {
const n = boxes.length
const answer = Array(n).fill(0)

let balls = 0
let operations = 0
for (let i = 0; i < n; i++) {
answer[i] = answer[i] + operations
balls = balls + Number(boxes[i])
operations += balls
}
balls = 0
operations = 0

for (let i = n - 1; i >= 0; i--) {
answer[i] = answer[i] + operations
balls = balls + Number(boxes[i])
operations += balls
}
return answer
}

/**
* 무지성 해답
*/
var minOperations = function (boxes) {
let arr = []
for (let i = 0; i < boxes.length; i++) {
let sum = 0
for (let j = 0; j < boxes.length; j++) {
if (boxes[j] == 1) {
sum += Math.abs(i - j)
}
}
arr.push(sum)
}
return arr
}

console.log(minOperations("110"))