Skip to content

Instantly share code, notes, and snippets.

@minisoba
Created April 20, 2019 21:35
Show Gist options
  • Save minisoba/f75e1c679c1d122615d69605918684a6 to your computer and use it in GitHub Desktop.
Save minisoba/f75e1c679c1d122615d69605918684a6 to your computer and use it in GitHub Desktop.
//
#include <iostream>
using namespace std;
struct StockPrice {
struct P {
long buy;
long sell;
P() : buy(0), sell(0) {
}
};
// collect a buy / sell and maximise a profit on stock price series
void compute(const vector<string>& v) {
P walk;
vector<P> res;
for (const auto& it : v) {
auto num = strtol(it.c_str(), NULL, 0);
if ((!walk.buy && !walk.sell) || (walk.buy > num && !walk.sell)) {
// finding local minima
walk.buy = num;
}
else if (!walk.sell || (walk.buy && walk.sell < num)) {
walk.sell = num;
}
else {
res.emplace_back(walk);
walk = P();
walk.buy = num;
}
}
if (walk.buy && walk.sell) {
res.emplace_back(walk);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment