[LeetCode]121 Best Time to Buy and Sell Stock
2015-01-06 17:44
399 查看
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
http://blog.csdn.net/linhuanmars/article/details/23162793
http://blog.csdn.net/linhuanmars/article/details/23162793
public class Solution { public int maxProfit(int[] prices) { // Solution A: return maxProfit_DP(prices); // Solution B: // return maxProfit_Binary(prices); } ///////////////////////////// // Solution A: DP // // global: 全局最优 // local: 在今天卖出的最优 // 在i-1 天卖出 的是 local // 在i天卖出的是 max(local + (price[i] - price[i - 1]), 0) private int maxProfit_DP(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; } ///////////////////////////// // Solution A: Binary // public int maxProfit_Binary(int[] prices) { if (prices == null || prices.length == 0) return 0; // Invalid input. Values value = calc(prices, 0, prices.length - 1); return value.pro; } private Values calc(int[] prices, int low, int high) { if (low == high) { return new Values(prices[low], prices[low], 0); } int mid = (low + high) / 2; Values left = calc(prices, low, mid); Values right = calc(prices, mid + 1, high); int max = Math.max(left.max, right.max); int min = Math.min(left.min, right.min); int pro = Math.max(left.pro, right.pro); pro = Math.max(pro, right.max - left.min); return new Values(max, min, pro); } private static class Values { Values(int max, int min, int pro) { this.max = max; this.min = min; this.pro = pro; } int max; int min; int pro; } }
相关文章推荐
- LeetCode: Best Time to Buy and Sell Stock [121]
- [Leetcode 121, medium] Best Time to Buy and Sell Stock I
- leetcode || 121、Best Time to Buy and Sell Stock
- leetcode-121 Best Time to Buy and Sell Stock
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- leetcode 121: Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- [Leetcode 37] 121 Best Time to Buy and Sell Stock
- leetcode 121 —— Best Time to Buy and Sell Stock
- LeetCode(121) Best Time to Buy and Sell Stock (Java)
- LeetCode 121: Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock - LeetCode 121
- leetcode解题报告:121 Best Time to Buy and Sell Stock
- Leetcode #121 Best Time to Buy and Sell Stock
- LeetCode(121)Best Time to Buy and Sell Stock
- leetcode[121]Best Time to Buy and Sell Stock
- [leetcode 121] Best Time to Buy and Sell Stock
- [LeetCode 121] - 买入与卖出股票的最佳时机(Best Time to Buy and Sell Stock)
- Leetcode 121 Best Time to Buy and Sell Stock 单次买卖股票最大收益
- Java for LeetCode 121 Best Time to Buy and Sell Stock