Skip to content

Instantly share code, notes, and snippets.

@luccabb
Created April 5, 2020 18:54
Show Gist options
  • Save luccabb/7c05ebe2546884abd878837865d87d63 to your computer and use it in GitHub Desktop.
Save luccabb/7c05ebe2546884abd878837865d87d63 to your computer and use it in GitHub Desktop.
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