Leetcode_Best Time to Buy and Sell Stock

时间:2023-03-10 06:36:08
Leetcode_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.

 从右到左扫描,维护一个当前节点右边最低的股价,用当前股价和最低股价的差作为最大收益交易的候选。扫描一遍,即可得最大收益。

class Solution {
public:
//I
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = prices.size();
if(len < ) return ; int min = prices[];
int res = ;
for(int i = ; i< prices.size(); ++i)
{
if(prices[i] < min){
min = prices[i] ;
continue;
}
res = res > prices[i] - min ? res : prices[i] - min ;
} return res;
}
};