欢迎来到Cefler的博客😁
🕌博客主页:折纸花满衣
🏠个人专栏:题目解析
🌎推荐文章:【LeetCode】winter vacation training
目录
- 👉🏻买卖股票的最佳时机
- 👉🏻买卖股票的最佳时机II
👉🏻买卖股票的最佳时机
原题链接:买卖股票的最佳时机
mycode:
class Solution {
public:int maxProfit(vector<int>& prices) {//贪心思路:低买高卖int min = INT_MAX,max = INT_MIN;int ret = 0;for(int i = 0;i<prices.size();i++){if(prices[i]<min) {min = prices[i];max = min;//卖出的时间必须大于等于买入时间}if(prices[i]>max) max = prices[i];if(max-min>ret) ret = max-min;//ret为最大利润}return ret;}
};
👉🏻买卖股票的最佳时机II
原题链接:买卖股票的最佳时机II
mycode:
class Solution {
public:int maxProfit(vector<int>& prices) {int min = INT_MAX, max = INT_MIN;int sum = 0;for (int i = 0; i < prices.size(); i++){if (prices[i] < min){min = prices[i];max = min;//卖出的时间必须大于等于买入时间}if (prices[i] > max) max = prices[i];sum += (max - min);if (max - min >0 )//必须要真的有利润获得{//min = INT_MAX, max = INT_MIN;//执行完买入卖出的操作后就重新恢复默认值进行重新准备买入卖出min = max = prices[i];//无论怎么样,买入卖出完后且获得利润,当前股票也要先入手//因为现在不先入手,下一次循环就要错过这天股票的买入}}return sum;
}
};
优化代码:
class Solution {
public:int maxProfit(vector<int>& prices) {int sum = 0;for(int i = 1;i<prices.size();i++){if(prices[i]>prices[i-1]) sum+= prices[i] - prices[i-1];}return sum;}
};