[leetcode]#121+122. Best Time to Buy and Sell Stock
来源:互联网 发布:yum 卡死 编辑:程序博客网 时间:2024/05/20 11:25
我们先拿出来前三道题,因为他们都是array中的题目。这是leetcode种经典的一系列题,涉及到动态规划和贪心算法。按照我的理解,贪心是满足当前条件的最优值我们就将它最为最优解,也就是大家说的局部最优值,而动态规划是要记录下来达到当前最优解的所有途径,由局部一步步得到全局最优。
这几道题都是给你一个股票每日价格表,让你得到不同条件下能挣的最多的钱。
- 121题是只允许买卖一次,要保证卖的时间晚于买的日期,第一反应找最大值和最小值,最大的早于最小的,那么就找次大和次小,这样肯定很麻烦,从这个过程已经能感受到一点动态规划的感觉。是的没错,这道题就是用动态规划,我们维持两个变量,最低买入价格和当前可达到的最高利润,从第二天开始遍历,小于最低价格那么我们更新最低价格变量,然后以这一天的价格作为卖出价格,那么利润就是卖出价格-最低价格,最次也就是0,也就是我更新了最低价格还以最低价格卖出去了,因为不能用之前的价格卖,此时利润也要相应的更新,大于保存的最大利润我们就更新,遍历完成后得到结果。
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if(len(prices) <= 1): return 0 buy_price = prices[0] max_profit = 0 for i in range(1,len(prices)): buy_price = min(buy_price, prices[i]) max_profit = max(max_profit, prices[i] - buy_price) return max_profit
- 122题是说不限制买卖股票的次数,只要保证你卖的日期晚于买的日期即可。这个就适合用贪心算法,只要当前比前一天的大,那么我们就卖了股票。
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ maxpro = 0 for i in range(1,len(prices)): if prices[i] > prices[i-1]: maxpro += prices[i] - prices[i-1] return maxpro
阅读全文
0 0
- [leetcode]#121+122. Best Time to Buy and Sell Stock
- LeetCode 122. Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- LeetCode #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- [LeetCode]122. Best Time to Buy and Sell Stock II
- Leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- LeetCode 122. Best Time to Buy and Sell Stock II
- LeetCode *** 122. Best Time to Buy and Sell Stock II
- leetcode-122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- 【LeetCode】122. Best Time to Buy and Sell Stock II
- C
- Ubuntu设置静态ip
- DC脚本命令(set_optimize_register)
- c语言传指针参数
- cocos创建Scene后一定要双击
- [leetcode]#121+122. Best Time to Buy and Sell Stock
- 在DOS界面怎么运行python的py文件
- 机器学习之训练集_验证集_测试集
- 网狐荣耀版进入手机客户端显示“获取服务器列表失败,是否重试?”怎么处理?
- AttributeError: 'dict' object has no attribute 'iteritems'
- 定时任务的时间格式配置
- IO(输入输出)-字节流
- JavaScript 对象(二)
- stmdb与ldmia