Created
September 24, 2020 11:30
-
-
Save codecakes/d40bd12e7a6f86a43de0adc9b199e36d to your computer and use it in GitHub Desktop.
Zigzag max min of sorted array including negative numbers
This file contains hidden or 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
| def max_min_negative(lst, n, new_min, new_max): | |
| res = [] | |
| for i in range(n//2): | |
| min_idx = i | |
| max_idx = n-i-1 | |
| res += [lst[max_idx], lst[min_idx]] | |
| if n%2 == 1: | |
| res[n-1] = lst[n//2] | |
| return res | |
| def max_min(lst): | |
| if not lst: | |
| return lst | |
| n = len(lst) | |
| new_min, new_max = 0, n-1 | |
| if any(i < 0 for i in lst): | |
| return max_min_negative(lst, n, new_min, new_max) | |
| maxNum = lst[-1] + 1 | |
| for idx in range(n): | |
| if idx%2 == 0: #max place | |
| lst[idx] += (lst[new_max] % maxNum) * maxNum | |
| new_max -= 1 | |
| else: #min place | |
| lst[idx] += (lst[new_min] % maxNum) * maxNum | |
| new_min += 1 | |
| for idx in range(n): | |
| lst[idx] //= maxNum | |
| return lst |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment