题目链接:
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.
输入
输入一个数组。
输出
最大利润。
样例输入
[7, 1, 5, 3, 6, 4] [7, 6, 4, 3, 1] |
样例输出
5 0 |
算法思想:
刚开始使用两次循环遍历,结果超时,后来改为一次循环,AC通过。
一次循环,使用mini记录之前最小的价格,ans之前的结果,如果当前数小于mini,则更新mini为当前数,否则如果ans小于prices[i] – mini,则更新ans。循环遍历完,ans存放的即为最大利润值。
源代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
if (sz == 0)
return 0;
int ans = 0, mini = prices[0];
for (int i = 0; i < sz; i++)
{
if (prices[i] < mini)
{
mini = prices[i];
}
else
{
if (ans < prices[i] - mini)
{
ans = prices[i] - mini;
}
}
}
return ans;
}
};
算法复杂度:
由源代码可知,算法只有一次循环,故时间复杂度为O(n)。