LeetCode 121 Best Time to Buy and Sell Stock题解
2016-12-05 13:33
417 查看
题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
给定一个数组,第i个数组元素的值表示第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.
如果你只被允许进行最多一次交易(即只允许买一次和卖一次股票),设计一个算法得到最大收益。
Example 1:
Example 2:
题目:
Say you have an array for which the ith element is the price of a given stock on day i.给定一个数组,第i个数组元素的值表示第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.
如果你只被允许进行最多一次交易(即只允许买一次和卖一次股票),设计一个算法得到最大收益。
Example 1:
Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0.
算法思想:
从数组头部开始遍历,用一个int型的变量记录遍历过的数值中的最小值,一个int型变量来记录盈利值,遍历时如果遍历的值比最小值还小,那么更新最小值,否则,判断是否要更新盈利值。Java代码实现:
public class Solution { public int maxProfit(int prices[]) { int minprice = Integer.MAX_VALUE; int maxprofit = 0; for (int i = 0; i < prices.length; i++) { if (prices[i] < minprice) minprice = prices[i]; else if (prices[i] - minprice > maxprofit) maxprofit = prices[i] - minprice; } return maxprofit; } }
相关文章推荐
- LeetCode 121. Best Time to Buy and Sell Stock 题解 —— Java
- LeetCode题解:121. Best Time to Buy and Sell Stock
- [LeetCode]题解(python):121-Best Time to Buy and Sell Stock
- LeetCode: Best Time to Buy and Sell Stock [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 37] 121 Best Time to Buy and Sell Stock
- leetcode121---Best Time to Buy and Sell Stock
- [Leetcode 121, medium] Best Time to Buy and Sell Stock I
- 【LeetCode从零单排】No121 Best Time to Buy and Sell Stock
- LeetCode121: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题解
- 【LeetCode】【Python题解】Best Time to Buy and Sell Stock II
- [LeetCode 121] - 买入与卖出股票的最佳时机(Best Time to Buy and Sell Stock)
- Java for LeetCode 121 Best Time to Buy and Sell Stock