LeetCode | Best Time to Buy and Sell Stock
2014-02-23 18:19
267 查看
题目
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.
分析
遍历一遍数组,遍历过程中,始终记录最小值,即遍历到当前节点所能看到的最佳买入价格。当被遍历节点不是最小值时,计算其与最小值的差价,从而判断是否有最大收益。
代码
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 BestTimeToBuyAndSellStock { public int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } int profit = 0; int min = prices[0]; for (int i = 1; i < prices.length; ++i) { if (prices[i] <= min) { min = prices[i]; } else { profit = Math.max(profit, prices[i] - min); } } return profit; } }
相关文章推荐
- leetcode--Best Time to Buy and Sell Stock
- [LeetCode] Best Time to Buy and Sell Stock II
- Leetcode算法学习日志-121 Best Time to Buy and Sell Stock
- leetcode_121题——Best Time to Buy and Sell Stock(动态规划)
- [LeetCode] Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III -- leetcode
- LeetCode - Best Time to Buy and Sell Stock
- [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 II
- leetcode-122 Best Time to Buy and Sell Stock II
- 【LeetCode】Best Time to Buy and Sell Stock(买卖股票的最佳时间)
- leetcode || 123、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 难度系数2 2.24
- leetcode 309 : Best Time to Buy and Sell Stock with Cooldown
- leetcode: Best Time to Buy and Sell Stock III
- leetcode:Best Time to Buy and Sell Stock II