Friday, July 24, 2015

max profit for stock prices

This logic returns 0 (avoids a buy/sale) if maxprofit is -ve.
(a):
    if a == null || a.length() == 0:
        throw
    maxlow = 0, maxhigh = 0
    low = 0
    for i = 0, i < a.length(), i++:
        if a[i] < a[low]:
            low = i
        if (a[i]-a[low]) > (a[maxhigh]-a[maxlow]):
            maxhigh = i
            maxlow = low
    return a[maxhigh] - a[maxlow]
[Hat tip to eopi]

This works if buy/sale is mandatory (-ve maxprofit).
(a):
    if a == null || a.length() < 2:
        throw
    low = 0
    maxlow = 0, maxhigh = 1
    for i = 1, i < a.length(), i++:
        if a[i]-a[low] > a[maxhigh]-a[maxlow]:
            maxhigh = i
            maxlow = low
        if a[i] < a[low]:
            low = i
    return a[maxhigh] - a[maxlow]
[Hat tip to IC]

No comments:

Post a Comment