121. Best Time to Buy and Sell Stock
Description :
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 104
solution1 暴力法
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = (int)prices.size(), ans = 0;
for (int i = 0; i < n; ++i){
for (int j = i + 1; j < n; ++j) {
ans = max(ans, prices[j] - prices[i]);
}
}
return ans;
}
};
复杂度分析
时间复杂度:O(n^2)O(n2 )。循环运行 \dfrac{n (n-1)}{2}
2
n(n−1) 次。
空间复杂度:O(1)O(1)。只使用了常数个变量。
solution2 一次遍历
算法
假设给定的数组为:[7, 1, 5, 3, 6, 4]
如果我们在图表上绘制给定数组中的数字,我们将会得到:
我们来假设自己来购买股票。随着时间的推移,每天我们都可以选择出售股票与否。那么,假设在第 i 天,如果我们要在今天卖股票,那么我们能赚多少钱呢?
显然,如果我们真的在买卖股票,我们肯定会想:如果我是在历史最低点买的股票就好了!太好了,在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的。那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice。
因此,我们只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?当考虑完所有天数之时,我们就得到了最好的答案。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int inf = 1e9;
int minprice = inf, maxprofit = 0;
for (int price: prices) {
maxprofit = max(maxprofit, price - minprice);
minprice = min(price, minprice);
}
return maxprofit;
}
};
复杂度分析
时间复杂度:O(n)O(n),只需要遍历一次。
空间复杂度:O(1)O(1),只使用了常数个变量。
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
solution3 DP
class Solution {
public:
int maxProfit(vector<int>& prices) {
int Min=INT_MAX, Max=0;
for(auto &x: prices){
Max = max(Max, x-Min); // 更新最大收益
Min = min(Min, x); // 更新最小值
}
return Max;
}
};
作者:nbgao
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/solution/nbgao-121-mai-mai-gu-piao-de-zui-jia-shi-swy0/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
solution4
class Solution {
public:
int maxProfit(vector<int>& prices) {
int mi = INT_MAX, res = 0;
for(int i : prices) {
if(i < mi) {
mi = i;
}
res = max(res, i - mi);
}
return res;
}
};
作者:distance66
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/solution/by-distance66-hmek/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
C++中1e9(初始化、无穷大)解析
https://blog.csdn.net/cpb____/article/details/107959450