As I suggested in the comments, you might want to do something like this. Sorry I can’t test right now, no guarantees!
template <class Iterator>
int bestProfit (Iterator begin, Iterator end)
{
int profit = 0;
for(;begin!=end; ++begin){
int p = *std::max_element(begin+1, end) - *begin;
profit = std:max(profit, p);
}
return profit;
}
Could also be quite elegant with a recursive function, as suggested somewhere in a comment.
The code above should probably skip the last loop iteration, come to think of it. What does std::max_element
return if both input iterators are identical?
EDIT:
You already have a working and accepted answer, but just for completeness sake (I guess I'm stubborn like that) here's my version of the recursive function. This does not have any explicit loops, but there is a loop inside of std::max_element
, and recursive functions a way of writing a loop. There is no way to visit all elements in a vector or list without a loop!
#include <vector>
#include <algorithm>
#include <iostream>
// Look mama! No `for`!
template <class Iterator>
int bestProfit (Iterator begin, Iterator end)
{
int buy = *begin;
++begin;
if (begin == end) return 0; // no profit to be had
int sell = *std::max_element(begin, end);
int profit = sell - buy; // max profit if we buy now
return std::max(profit, bestProfit(begin, end)); // will we do better if we wait?
}
int main() {
std::vector<int> prices1{38, 28, 30, 38, 34};
if (bestProfit(prices1.begin(), prices1.end()) != 10)
std::cout << "bad 1!\n";
std::vector<int> prices2{1, 2, 3, 4, 5, 0};
if (bestProfit(prices2.begin(), prices2.end()) != 4)
std::cout << "bad 2!\n";
std::vector<int> prices3{2, 3, 1, 4, 5, 0};
if (bestProfit(prices3.begin(), prices3.end()) != 4)
std::cout << "bad 3!\n";
std::vector<int> prices4{0, 1, 2, 5, 4, 3};
if (bestProfit(prices4.begin(), prices4.end()) != 5)
std::cout << "bad 4!\n";
std::vector<int> prices5{100, 200, 0, 1, 3};
if (bestProfit(prices5.begin(), prices5.end()) != 100)
std::cout << "bad 5!\n";
std::vector<int> prices6{100, 200, 0, 101, 30};
if (bestProfit(prices6.begin(), prices6.end()) != 101)
std::cout << "bad 6!\n";
}