121. Best Time to Buy and Sell Stock
来源:互联网 发布:centos 中英输入法转换 编辑:程序博客网 时间:2024/06/07 15:54
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 class Solution { public int maxProfit(int[] prices) { if (prices.length<=1) { return 0; } Integer[] mins = new Integer[prices.length]; // first n days Integer[] maxs = new Integer[prices.length]; // last n days mins[0] = prices[0]; maxs[prices.length-1] = prices[prices.length-1]; // fill max prices, from right to left for (int i=prices.length-2; i>=0; i--) { if (prices[i]>maxs[i+1]) maxs[i] = prices[i]; else maxs[i] = maxs[i+1]; } // fill min prices, and calculate the biggest profit, from left to right int biggestProfit = 0; for (int i=1; i<prices.length; i++) { if (prices[i]<mins[i-1]) mins[i] = prices[i]; else mins[i] = mins[i-1]; int profit = maxs[i] - mins[i]; if (profit>biggestProfit) biggestProfit = profit; } return biggestProfit; }}
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
- 哈希表
- 高光谱遥感图像处理(11)----ENVI建立矢量数据
- [BZOJ2060][Usaco2010 Nov]Visiting Cows 拜访奶牛(树形dp)
- Androidn Notification的使用,解决找不到setLatestEventInfo方法
- FormData实现异步传送带文件的表单
- 121. Best Time to Buy and Sell Stock
- 【日常小记】linux中强大且常用命令:find、grep
- int和Integer有什么区别?
- socket服务器代码
- 数据库学习笔记
- Android中的Audio播放:音量和远程播放控制
- 泛型总结
- 119. Pascal's Triangle II
- 数组指针和指针数组