Created
February 25, 2023 00:28
-
-
Save germanescobar/f2660e0bd45a8ca56666f8b92ebf1c8f to your computer and use it in GitHub Desktop.
This file contains 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
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