This is a Javascript implementation for a solution to the CodinGame Stock Exchange Losses problem.

The post is the fourth in a series that I started with the goal of testing the feasibility of solving CodinGame challenges in Javascript. You can also check out the third and second solutions that I posted earlier.

There is a naive O(n^2) solution to this problem which compares each element to all subsequent elements keeping track of the global minimum (maximal difference) found. This is trivial to implement using two nested for loops

However, this algorithm is sub-optimal and it's quadratic performance characteristics start to take a toll on larger sequences.

In contrast with the trivial O(n^2) implementation, the algorithm I gave in the complete solution computes the result in linear time by keeping track of two differences: a local difference which is updated whenever a new larger price is detected, and a global difference which is the largest (maximal) difference for all prices so far