Skip to content

Instantly share code, notes, and snippets.

@rishabhgargg
Created July 19, 2024 13:50
Show Gist options
  • Save rishabhgargg/78f4d7a57c1e7b39186cc4a022af8cac to your computer and use it in GitHub Desktop.
Save rishabhgargg/78f4d7a57c1e7b39186cc4a022af8cac to your computer and use it in GitHub Desktop.
def max_subarray_cost(arr):
if not arr:
return 0
max_sum = arr[0]
current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum ** 2
# Test cases
arr1 = [1, -1, 1, -1, 1]
arr2 = [1, 2, 3]
arr3 = [-2, -3, -1, -5]
arr4 = [0, 0, 0, 0]
arr5 = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(max_subarray_cost(arr1)) # Output: 1
print(max_subarray_cost(arr2)) # Output: 36
print(max_subarray_cost(arr3)) # Output: 1
print(max_subarray_cost(arr4)) # Output: 0
print(max_subarray_cost(arr5)) # Output: 16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment