Last active
May 19, 2023 02:26
-
-
Save Shaddyjr/b50acadc193bbd057abdb851859731c1 to your computer and use it in GitHub Desktop.
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
// source: https://www.hackerrank.com/challenges/equal/problem | |
// video: https://youtu.be/Mbfs-4URYmg | |
function equal(arr) { | |
let rounds = Infinity | |
const min = Math.min(...arr) | |
// Go through each target value (min, min-1, min-2, ..., min-4) | |
for (let n = 0; n < 5; n++){ // O(5) = O(1) | |
const target = min - n | |
let operationCount = 0 | |
// Go through each value in arr... | |
for (const val of arr){ // O(n) | |
// calculate difference b/t val and target | |
const diff = val - target | |
// use modular math and add to operationCount | |
const fiveCount = Math.floor(diff / 5) | |
const twoCount = Math.floor((diff % 5) / 2) | |
const oneCount = (diff % 5) % 2 | |
operationCount += fiveCount + twoCount + oneCount | |
} | |
rounds = Math.min(rounds, operationCount) | |
} | |
return rounds // Time Complexity = O(n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment