leetcode--Best Time to Buy and Sell Stock
来源:互联网 发布:在淘宝买手机是真品吗 编辑:程序博客网 时间:2024/05/16 05:51
题目大概意思是说,给一个整形数组,每个数表示股票的成交价,然后由你决定哪一天买进,哪一天卖出使得利益最大。注意一下,要先买进,同一天是可以买进卖出的,只是利益为零。
动态规划基本题,将大问题转换为一个个阶段的小问题。用buy指示在哪一天买,sell指示哪一天卖,每完成一次买卖,用profit存下获益值,每个阶段都会产生一个profit,并比较阶段内最适合的买进值,存为下一阶段的buy值。
逻辑比较简单,直接代码吧。
public class Solution { public int maxProfit(int[] prices) { if(prices.length==0)return 0; int buy = prices[0]; int sell = 0; int profit = 0; for(int price:prices){ sell = price; profit = Math.max(profit,sell-buy); buy = Math.min(buy,price); } return profit; }}
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- css line-height:150%和1.5的不同之处
- Shell编程(四)---echo、printf
- 基于TestNG 与Selenium 的自动化测试设计与实施(二)
- Fragment详解(四)Fragment生命周期
- spring3.1以上利用 ehcache进行注解配置缓存不起作用的原因
- leetcode--Best Time to Buy and Sell Stock
- iOS 网络问题
- ORACEL存储过程中声明一个可存储记录的像数据表一样的变量的简便方法。
- 总结下并行和并发的差异
- mac 定时任务
- Linux学习--rsync同步备份实现
- C#课后练习题(二)
- POJ 2236 Wireless Network
- jQuery.serialize() 函数详解