You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
解法一:
贪心法。遍历数组,计算当天能达到的最大利润,取其中的最大值。代码如下:
classSolution {
public:intmaxProfit(vector<int>& prices) {
int mi = INT_MAX, res = 0;
for (auto price: prices) {
if (price < mi) {
mi = price;
}
res = max(res, price - mi);
}
return res;
}
};
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:
Example 2:
Constraints:
解法一:
贪心法。遍历数组,计算当天能达到的最大利润,取其中的最大值。代码如下:
解法二:
动态规划。
dp[i][0]表示第i天持有股票所获得的的最大现金, dp[i][1]表示第i天不持有股票所获得的的最大现金。
对于dp[i][0],它有两种来源:
综上:dp[i][0] = max(dp[i-1][0], -prices[i])
对于dp[i][1],它有两种来源:
综上:dp[i][1] = max(dp[i-1][1], prices[i]+dp[i-1][0])
图示如下:

代码如下:
解法三:
动态规划。利用统一的框架:动态规划总结: 股票买卖问题进行推导,代码如下:
Refer:
团灭 LeetCode 股票买卖问题
The text was updated successfully, but these errors were encountered: