正如我在 cmets 中建议的那样,您可能想做这样的事情。抱歉,我现在无法测试,无法保证!
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;
}
正如评论中的某处所建议的那样,使用递归函数也可以非常优雅。
上面的代码可能应该跳过最后一次循环迭代,想想看。如果两个输入迭代器相同,std::max_element 返回什么?
编辑:
您已经有了一个可行且可接受的答案,但为了完整起见(我想我很固执)这是我的递归函数版本。这没有任何显式循环,但std::max_element内部有一个循环,递归函数是一种编写循环的方式。没有循环就无法访问向量或列表中的所有元素!
#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";
}