New year resolutions

So it’s that time of year where people have figured out that they were guilty of certain things in 2013, which they are giving up for a few weeks in 2014 (i.e. new year’s resolutions).

I’m guilty of not reading as much as when I was a kid, so I’ve decided to take the ’52 book week challenge’ for 2014, on average a book a week. I’ll be keeping track of my progress in this post, and hopefully as it’s public I’ll try and complete the challenge!

Only time will tell…

Current book count = 3

1) Choose Yourself – James Altucher
2) Bloomberg by Bloomberg
3) The 4-hour body – Tim Ferriss
4) Eleven Minutes – Paulo Coelho
5) No Exit –¬†Gideon Lewis-Kraus

EDIT : As it’s nearly midway through the year and I’m busy, this target has been changed to 20 books!

Maximum continous sequence profit

An interesting concept in Finance and Computer Science is if we have some historical data about the price of a security and we want to see the maximum profit we can make. (Assumption: we can only carry out one buy and one sell action)

Let’s assume that time is represented by natural numbers as opposed to timestamps. With this, we can represent the prices as an array and the index of the array representing the timestamp value (the lower values being earlier prices).

So given the array: [4.5, 6.0, 4.2, 4.4, 7.0, 3.2] the maximum profit we can make is 7.0 Р4.2 = 2.8

The solution may seem tricky as there are local sub-array problems that need to be solved, for example if we have gone through the first four elements of the array above, we can’t really say anything about the profit until we see more elements of the array.

The solution that I came up with had two variables and keeps track of the current maximum profit by continuous calculation and the minimum price value. This concept surprisingly leads to an elegant solution.

My solution (implemented in Python) is below, it’s got a complexity of O(n) – there has to be at least one element in the array.

[sourcecode language=”python”]

def max_profit(array):
profit = 0
min = array[0]
for i in array:
if i < min:
min = i
if (i – min > profit):
profit = (i – min)
return profit

[/sourcecode]