Skip to content

Instantly share code, notes, and snippets.

@germanescobar
Created February 25, 2023 00:28
Show Gist options
  • Save germanescobar/f2660e0bd45a8ca56666f8b92ebf1c8f to your computer and use it in GitHub Desktop.
Save germanescobar/f2660e0bd45a8ca56666f8b92ebf1c8f to your computer and use it in GitHub Desktop.
var minimumDeviation = function(nums) {
nums.sort((a,b) => a - b)
let diff = nums[nums.length-1] - nums[0]
let diffExt = nums[0] !== nums[nums.length-1]
let canOperate = nums[0] % 2 !== 0 || nums[nums.length-1] % 2 === 0
while (diffExt && canOperate && diff > 1) {
console.log(nums, diff)
let oper = false
if (nums[0] % 2 !== 0) {
oper = true
nums[0] *= 2
}
if (nums[nums.length-1] % 2 === 0) {
oper = true
nums[nums.length-1] /= 2
}
if (!oper) break
let stop = false
for (let i=0; i < nums.length && !stop; i++) {
if (nums[i] > nums[i+1]) {
const aux = nums[i+1]
nums[i+1] = nums[i]
nums[i] = aux
} else {
stop = true
}
}
stop = false
for (let i=nums.length-1; i > 0 && !stop; i--) {
if (nums[i] < nums[i-1]) {
const aux = nums[i-1]
nums[i-1] = nums[i]
nums[i] = aux
} else {
stop = true
}
}
const newDiff = nums[nums.length-1] - nums[0]
if (newDiff > diff) {
break
}
diff = nums[nums.length-1] - nums[0]
diffExt = nums[0] !== nums[nums.length-1]
canOperate = nums[0] % 2 !== 0 || nums[nums.length-1] % 2 === 0
}
return nums[nums.length-1] - nums[0]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment