Best Time to Buy and Sell Stock - LeetCode

时间:2023-11-09 22:43:20

题目链接

Best Time to Buy and Sell Stock - LeetCode

注意点

  • 在卖出之前必须要先购入

解法

解法一:遍历一遍,随时记录当前数字之前的最小的数字。将当前数字与当前最小数字相减查看收益。时间复杂度O(n)

class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if(size < 1) return 0;
int max = 0,min = prices[0];
for(int i = 1;i < size;i++)
{
if(prices[i] - min > max) max = prices[i] - min;
if(prices[i] < min) min = prices[i];
}
return max;
}
};

Best Time to Buy and Sell Stock - LeetCode

小结