121. Best Time to Buy and Sell Stock
来源:互联网 发布:js打开网页弹出提示框 编辑:程序博客网 时间:2024/05/16 05:03
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.
Solution 1
public static int maxProfit(int[] prices) {int max = 0;int min = Integer.MAX_VALUE;for (int i = 0; i < prices.length; i++) {min = Math.min(prices[i], min);max = Math.max(max, prices[i] - min);}return max;}
Solution 2 Optimization
//Optimization on the first onepublic int maxProfit3(int[] prices) { if(prices == null || prices.length < 2) return 0; int maxProfit = 0, minPrice = prices[0]; for(int i = 1; i < prices.length; i++) { if(prices[i] > prices[i - 1]) { maxProfit = Math.max(maxProfit, prices[i] - minPrice); } else { minPrice = Math.min(minPrice, prices[i]); } } return maxProfit;}
Solution 3
// O(N * N)public static int maxProfit2(int[] prices) {if (prices.length < 2)return 0;int diff[] = new int[prices.length - 1];for (int i = 1; i < prices.length; i++) {diff[i - 1] = prices[i] - prices[i - 1];}return maxSubArray(diff);}public static int maxSubArray(int[] nums) {if (nums.length < 1)return 0;int preMax = 0, max = 0;for (int i = 0; i < nums.length; i++) {max = Math.max(max, preMax + nums[i]);preMax = Math.max(0, preMax + nums[i]);}return max;}
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Alibaba-AndFix Bug热修复框架的使用
- Android-FixBug热修复框架的使用及源码分析(不发版修复bug)
- 创业者合伙人很重要
- 读论文BinarizedNormedGradientsforObjectnessEstimationat300fps
- 11. Container With Most Water
- 121. Best Time to Buy and Sell Stock
- shell脚本抽取文本文件中指定字符串的方法:sed+grep方法、awk+grep方法(必要时可以联合sed以及grep)、grep+cut方法
- shell:读取文件的每一行内容并输出
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- iOS加载任意类型图片(不加后缀名)
- poj 1874 Tram
- 怎样计算C++继承、虚继承、虚函数类的大小
- android 系统内存检查
- HDU 4847 Wow! Such Doge!