LeetCode Best Time to Buy and Sell Stock
来源:互联网 发布:显微镜图像测量软件 编辑:程序博客网 时间:2024/06/10 13:21
原题链接在这里:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
与Maximum Subarray相似,都是全局最优与局部最优问题。
维护一个局部最优解,和一个全局最优解, 先更新局部最优解, 要么是原来的局部最优加上i天与i-1天得差价,要么是0(i天股价没有i-1天高), 然后维护全局最优,最后返回全局最优。
AC Java:
public class Solution { public int maxProfit(int[] prices) { //采用局部最优和全局最优 if(prices == null || prices.length <= 1){ return 0; } int local = 0; int global = 0; for(int i = 1; i<prices.length; i++){ local = Math.max(local+prices[i]-prices[i-1],0); global = Math.max(local,global); } return global; }}
后面有多个进阶版本。
Best Time to Buy and Sell Stock II
Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock IV
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
- hdu1827 Summer Holiday(tarjan+ 缩点)
- Android工具类之图片流InputStream->(byte[])->Bitmap/Drawable
- ML基石_4_FeasibilityOfLearning
- sql 分页
- Log4j配置整理
- LeetCode Best Time to Buy and Sell Stock
- Linux内核工程导论——总线:Platform
- 7.Reverse Integer
- java 读取txt文件内容(一)
- 记一次进不了Win7系统的情况
- 为跨平台数据库引擎 SQLite 实现加密扩展
- 蓝懿教育 通讯录
- HTTP状态码概要和REST常用状态码
- openwrt luci界面修改