Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Last active May 19, 2023 02:26
Show Gist options
  • Save Shaddyjr/b50acadc193bbd057abdb851859731c1 to your computer and use it in GitHub Desktop.
Save Shaddyjr/b50acadc193bbd057abdb851859731c1 to your computer and use it in GitHub Desktop.
// 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