Skip to content

Instantly share code, notes, and snippets.

@Mazyod

Mazyod/max_slice.py

Created Oct 2, 2016
Embed
What would you like to do?
Max slice explained
# starting array
A = [5, -2, 10, 3, -25, 12, 6]
# calculating the max slice in O(n), starting from A[1]
# copy A into S, where the max slices are stored
S = A[:]
# instead of looping, I'll unroll the loop for simplicity
# so, at S[1], we either add the previous sum, or start over
# to decide that, we simply check the max between the element and the previous sum added
S[1] = max(S[1], S[1] + S[0])
# S = [5, 3, ...]
S[2] = max(S[2], S[2] + S[1])
# S = [5, 3, 13, ...]
# S = [5, 3, 13, 16, ...]
# S = [5, 3, 13, 16, -9, ...]
# S = [5, 3, 13, 16, -9, 12, ...]
# S = [5, 3, 13, 16, -9, 12, 18]
# answer = max(S)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.