@requires_authorization
@author johnsondu
@create_time 2015.7.19 21:01
@url [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)
/************************
* @description: dynamic programming.
* 相邻元素做差,求出所有非负元素的和
* @time_complexity: O(n)
* @space_complexity: O(1)
************************/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int p_size = prices.size();
if(p_size < 2) return 0;
int ans = 0;
for(int i = 1; i < p_size; i ++) {
int tmp = prices[i] - prices[i-1];
if(tmp > 0) ans += tmp;
}
return ans;
}
};
【leetcode】122.Best Time to Buy and Sell Stock II
最新推荐文章于 2025-04-18 22:24:21 发布
本文介绍使用动态规划算法解决股票买卖问题中的最大利润计算,通过相邻元素做差求得所有非负元素的和,实现O(n)的时间复杂度和O(1)的空间复杂度。
404

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



