【LeetCode】Best Time to Buy and Sell Stock

时间:2021-02-14 08:50:29

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.

code : 朴素的算法,对每一个i ,计算 最大 的 prices[j] (j>i) 来维护最大的差值,但是这样的复杂度是O(n^2),会TLE

考虑下面的O(n)算法:

class Solution {
public:
int maxProfit(vector<int> &prices) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int maxsum = 0;
if(prices.size() <= 1)
return 0; int maxPrice = prices.back();
for(int i = prices.size()-1; i >= 0; i--)
{
maxPrice = max(maxPrice,prices[i]);
maxsum = max(maxsum,maxPrice-prices[i]);
}
return maxsum ; }
};