Leecode121. Best Time to Buy and Sell Stock
买卖股票的最好时机
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.
Subscribe to see which companies asked this question
解题思路:使用在线处理方法 O(n)时间复杂度
当然也可以使用循环依次求出差值,最大的差值即为结果 时间复杂度为O(n^2)
C++ 代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n <= 1)
return 0;
int Max = prices[n - 1];
int value = 0;
int Maxprofit = 0;
int i;
for (i = n - 1; i >= 0; i--)
{
if (prices[i]>Max)
Max = prices[i];
value = Max - prices[i];
if (value>Maxprofit)
Maxprofit = value;
}
return Maxprofit;
}
};