Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.、
分析:相较于同系列题目的II,这道题我觉得跟家有难度。我选择设置变量min和result。min是已经遍历过的最小值,result是现在的值和最小值之差的最大值,以此来获得答案。
代码:#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() == 0) return 0;
int re = 0;
int min = prices[0];
for (int i = 1; i < prices.size(); i++) {
if (prices[i] < min) min = prices[i];
if (re < prices[i] - min) re = prices[i] - min;
}
return re;
}
};