Created
July 6, 2018 15:22
-
-
Save pdu/e19be7a44a74d75f8cf6fda113bda140 to your computer and use it in GitHub Desktop.
give an array n and integer k, for each element in the array, you have to whether +k or -k. try to find the minimum gap between the largest value and smallest value after the operations
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
#!/usr/bin/env python | |
""" | |
give an array n and integer k, for each element in the array, you have to whether +k or -k | |
try to find the minimum gap between the largest value and smallest value after the operations | |
""" | |
def find1(arr, k): | |
arr2 = [] | |
for i in xrange(0, len(arr)): | |
arr2.append((arr[i] - k, i)) | |
arr2.append((arr[i] + k, i)) | |
arr2.sort() | |
min_gap = arr2[-1][0] - arr2[0][0] | |
for i in xrange(0, len(arr2)): | |
min_value, max_value = arr2[i][0], arr2[i][0] | |
elements = {} | |
for j in xrange(i, len(arr2)): | |
elements[arr2[j][1]] = True | |
max_value = arr2[j][0] | |
if len(elements) == len(arr): | |
break | |
if len(elements) == len(arr): | |
min_gap = min(min_gap, max_value - min_value) | |
return min_gap | |
if __name__ == "__main__": | |
print find1([0, 2, 4, 10], 3) | |
print find1([1, 2, 3], 100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment