对于dp的问题归纳的总结。在文章中的体现的。
方式一:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minprice = float('inf')
maxprofit = 0
for price in prices:
minprice = min(minprice, price)
maxprofit = max(maxprofit, price - minprice)
return maxprofit
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n == 0) return 0; // 边界条件
int minprice = prices[0];
vector<int> dp (n, 0);
for (int i = 1; i < n; i++){
minprice = min(minprice, prices[i]);
dp[i] = max(dp[i - 1], prices[i] - minprice);
}
return dp[n - 1];
}
};

本文深入探讨了股票买卖最佳时机的算法实现,通过动态规划方法寻找最大利润。提供了Python和C++两种语言的代码示例,展示了如何通过维护最低购买价格和最大利润来解决这一经典问题。
1717

被折叠的 条评论
为什么被折叠?



