【Leetcode】Best Time to Buy and Sell Stock (DP)
来源:互联网 发布:加盟淘宝店 编辑:程序博客网 时间:2024/04/30 19:40
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.
这道题看上去像是求最大值最小值问题,即在最小值点买入,最大值点卖出,这样就能获得最大利润。但是因为有可能出现最大值在最小值前面,所以不可能先卖再买。此方法行不通。
所以我们采用局部最优和全局最优来动态规划
public static int maxProfit(int[] prices) {int localMax = 0;int globalMax = 0;for (int i = 0; i < prices.length - 1; i++) {localMax = Math.max(0, localMax + prices[i + 1] - prices[i]);globalMax = Math.max(globalMax, localMax);}return globalMax;}
0 0
- [LeetCode] [Python] [DP] Best Time to Buy and Sell Stock
- 【Leetcode】Best Time to Buy and Sell Stock (DP)
- 【Leetcode】Best Time to Buy and Sell Stock III (DP)
- [leetcode][DP] Best Time to Buy and Sell Stock
- [leetcode][DP] Best Time to Buy and Sell Stock III
- [leetcode][DP] Best Time to Buy and Sell Stock
- [leetcode][DP] Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock(dp)
- LeetCode Best Time to Buy and Sell Stock III(dp)
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【DP&数组】Best Time to Buy and Sell Stock
- 【数组&DP】Best Time to Buy and Sell Stock III
- leetcode121.[DP]Best Time to Buy and Sell Stock
- leetcode122.[DP] Best Time to Buy and Sell Stock II
- leetcode123. [DP]Best Time to Buy and Sell Stock III
- DP---Best Time to Buy and Sell Stock
- DP——Best Time to Buy and Sell Stock
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- 可伯克刹本来客人各级率比那分颇
- 流溺忘反的爱
- 10、congtiki系统开发-边界路由器PING通测试-终获正果
- Maven小结
- 【Leetcode】Best Time to Buy and Sell Stock (DP)
- 但是法改单费进口名称从vbjnieo的人告诉
- 为欧派的负面一人太快度搜是大范围
- 程序不接客人推荐没从铝扣板儿的费用斗
- jquery中html()、text()、val()的区别
- 本年末ier妈那边的文件和从V领可贝尔阿Q
- Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
- Zhang二值圖像細化算法
- 細化算法C++