#leetcode#Best Time to Buy and Sell Stock
来源:互联网 发布:美国协同办公软件 编辑:程序博客网 时间:2024/05/08 17:38
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
首先想到的是扫两边, 先找到最大值, 然后找到最大值前面的最小值, 相减得到最大的profit,但是这样的话[4, 1, 2]就会返回0, 应该是1买进, 2卖出, 这样profit为1.
问题想的太简单了。
所以正确的brute force是对每一个元素,计算于其身后的所有可能的profit, 时间复杂度为O(n^2)。
DP思路还是借鉴了Code Ganker大神, 维护两个变量, local = 0, global = 0。
local = Math.max(local + prices[i + 1] - prices[i], 0) ...... 局部变量如果走到某一节点处变为负数, 则最大利益交易有可能已经出现, 或者还在后面。
global = Math.max(global, local)
http://blog.csdn.net/linhuanmars/article/details/23162793
- 【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
- PAT-A 1013. Battle Over Cities (25)
- Android性能优化之解密ZAKER,网易云阅读等新闻应用的内容缓存加载方式
- 2015最新过360版GSMS双网软件ISO文件下载
- discuz的微信登录与首页面整合
- iPhone图形开发绘图小结
- #leetcode#Best Time to Buy and Sell Stock
- HTML 学习思维导图
- Qt5下OpenGL程序的新写法
- scv.lua (可能还需完善)
- iOS: 使用CGContextRef,CGPath和UIBezierPath来绘画
- Core Graphics路径CGPath
- java面试之finally与return
- 人生到此初相见——北漂18年(10)
- weka实战002:apriori关联规则算法