|
| 1 | +# Minimum Difference Between Largest and Smallest Value in Three Moves |
| 2 | +# https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/ |
| 3 | +# Solution idea taken from https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/730567/JavaC%2B%2BPython-Straight-Forward |
| 4 | + |
| 5 | +class Solution(object): |
| 6 | + |
| 7 | + def kill1Big2Small(self, array): |
| 8 | + array[len(array)-1] = array[len(array)-2] |
| 9 | + array[0] = array[1] = array[2] |
| 10 | + |
| 11 | + def kill2Big1Small(self, array): |
| 12 | + array[len(array)-1] = array[len(array)-2] = array[len(array)-3] |
| 13 | + array[0] = array[1] |
| 14 | + |
| 15 | + def kill3Smallest(self, array): |
| 16 | + array[0] = array[1] = array[2] = array[3] |
| 17 | + |
| 18 | + def kill3Biggest(self, array): |
| 19 | + array[len(array)-1] = array[len(array)-2] = array[len(array)-3] = array[len(array)-4] |
| 20 | + |
| 21 | + def minDifference(self, nums): |
| 22 | + # if nums length is less than or equal to 4 |
| 23 | + # so in that case we replace all elements with 1 element and the answer is 0 |
| 24 | + if (len(nums) <= 4): |
| 25 | + return 0 |
| 26 | + # Sort the array and Kill 3 biggest elements |
| 27 | + threeBig = sorted(nums) |
| 28 | + self.kill3Biggest(threeBig) |
| 29 | + threeBigDifference = max(threeBig) - min(threeBig) |
| 30 | + # Sort the array and kill 3 smallest elements |
| 31 | + threeSmall = sorted(nums) |
| 32 | + self.kill3Smallest(threeSmall) |
| 33 | + threeSmallDifference = max(threeSmall) - min(threeSmall) |
| 34 | + # Sort the array and kill 2 big and 1 small |
| 35 | + twoBigOneSmall = sorted(nums) |
| 36 | + self.kill2Big1Small(twoBigOneSmall) |
| 37 | + twoBigOneSmallDifference = max(twoBigOneSmall) - min(twoBigOneSmall) |
| 38 | + # Sort the array and kill 1 big and 2 small |
| 39 | + oneBigTwoSmall = sorted(nums) |
| 40 | + self.kill1Big2Small(oneBigTwoSmall) |
| 41 | + oneBigTwoSmallDifference = max(oneBigTwoSmall) - min(oneBigTwoSmall) |
| 42 | + return min(threeBigDifference, threeSmallDifference, twoBigOneSmallDifference, oneBigTwoSmallDifference) |
| 43 | + """ |
| 44 | + :type nums: List[int] |
| 45 | + :rtype: int |
| 46 | + """ |
| 47 | + |
0 commit comments