Problem : Given an array A of integers, maximize A[j] - A[i] such that 0 <= i < j < len(A).
A very interesting problem, as always lets begin with a naive solution.
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
def max_diff_naive(L): | |
max_diff = start = end = 0 | |
for i in xrange(len(L)): | |
for j in xrange(i+1,len(L)): | |
if max_diff < L[j] - L[i]: | |
start,end = i,j | |
max_diff = L[j] - L[i] | |
return max_diff,start,end |
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
def max_diff_linear(L): | |
min_index = 0 | |
max_diff = start = end = 0 | |
for i in xrange(len(L)): | |
if L[i] < L[min_index]: min_index = i | |
if max_diff < L[i] - L[min_index]: | |
max_diff = L[i] - L[min_index] | |
start,end = min_index,i | |
return max_diff,start,end |
Update: So I just discovered this problem is called the Single Sell Profit problem. It's been discussed quite thoroughly by templatetypedef here. It includes 4 solutions (including this one).
Comments
Post a Comment