Created
January 23, 2020 22:25
-
-
Save crates/e835e7ab7f31d217819345ba5c83c274 to your computer and use it in GitHub Desktop.
Find the minimum number of moves to make all washing machines have the same number of dresses (LeetCode)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Designed to solve this LeetCode problem: https://leetcode.com/problems/super-washing-machines/ | |
// Author: Crates McD (https://cr8s.net) | |
// Runtime: 52 ms, faster than 100.00% of JavaScript online submissions for Super Washing Machines. | |
// Memory Usage: 35 MB, less than 100.00% of JavaScript online submissions for Super Washing Machines. | |
// Time complexity: O(n); space complexity: O(1) | |
/** | |
* @param {number[]} machines | |
* @return {number} | |
*/ | |
const findMinMoves = (machines) => { | |
const sum = machines.reduce((sum, num) => sum + num, 0); | |
const avg = Math.floor(sum / machines.length); | |
let ans = 0; | |
let rightTotal; | |
if (avg * machines.length !== sum) return -1; | |
for(let i = 0, leftTotal = 0; | |
i < machines.length; | |
leftTotal += machines[i++] | |
) { | |
machines[i] -= avg; | |
rightTotal = -leftTotal - machines[i]; | |
ans = Math.max(ans, | |
Math.max(0, -leftTotal) + Math.max(0, -rightTotal) | |
); | |
} | |
return ans; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment