类别:dynamic programmin
难度:easy
题目描述
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
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.
(买入的时间必须要比卖出的时间早,即后面的数字要比前面的大)
算法分析
只需要遍历数组,维护一个最小价格,每到一个价格的时候,比较当前能够获得的最大利益(即当前价格减去最小价格),将当前的最大利益与之前已经得到的最大利益进行比较取最大值。
比较简单,理解即可实现。
代码实现
#include <iostream>
#include <vector>
using namespace std;
// cur - min = curmax
// max(max, curmax)
int maxProfit(vector<int>& prices) {
int minPrice = 10000;
int n = prices.size();
int result = 0;
for (int i = 0; i < n; ++i) {
minPrice = (minPrice < prices[i]) ? minPrice : prices[i];
result = (prices[i] - minPrice) > result ? prices[i] - minPrice : result;
}
return result;
}
int main() {
int n;
int num;
vector<int> data;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> num;
data.push_back(num);
}
cout << maxProfit(data) << endl;
return 0;
}