Created
April 5, 2020 18:54
-
-
Save luccabb/7c05ebe2546884abd878837865d87d63 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
import math | |
def max_subarray(x): | |
# starting array to make any subarray bigger than its value | |
maxSubarray = [-(math.inf)] | |
# looping through all the array to find the maxsubarray | |
# bruteforce approach | |
for j in range(len(x)): | |
for i in range(j+1, len(x)+1): | |
if sum(x[j:i]) > sum(maxSubarray): | |
maxSubarray = x[j:i] | |
return maxSubarray | |
print(max_subarray([0,0,-1,2,3,3,-2,9])) | |
def incremental_max_subarray(x, mx): | |
# comparing the max subarray sum (mx), to the last value of x | |
# returning the highest one. | |
return mx + x[-1] if mx +x[-1] > mx else mx | |
print(incremental_max_subarray([1,2,3,4], 6)) | |
def pairs(x): | |
# starting pointers | |
j=0 | |
i=0 | |
farthest = -(math.inf) | |
closest = math.inf | |
# looping through all the array to find the largest and smallest difference | |
# between 2 numbers | |
for a in range(len(x)): | |
for b in range(a+1, len(x)): | |
if abs(x[a] - x[b]) > farthest: | |
farthest = abs(x[a] - x[b]) | |
if abs(x[a] - x[b]) < closest: | |
closest = abs(x[a] - x[b]) | |
return farthest, closest | |
print(pairs([1,2,7, 8 , 3 , 5])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment