[LeetCode] NO. 121 Best Time to Buy and Sell Stock
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] NO. 121 Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。
[题目]
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.
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.
[题目解析] 根据题意,求最大收益,即求数组中prices[j] - prices[i] 的最大值,其中,j>i。最直接的思路是遍历求每一对prices[j]-prices[i],取出最大值即可。如下。
public int maxProfit(int[] prices) { int profit = 0; for(int i = 0; i < prices.length; i++){ for(int j = i+1; j < prices.length; j++){ if(prices[j] - prices[i] > profit){ profit = prices[j] - prices[i]; } } } return profit; }
在LeetCode上面提交,出现Time Limit Exceeded异常,时间复杂度是O(n2),接下来需要优化下,找出时间复杂度低的方法。
上面的方法我们做了很多没必要的工作,我们进行一次循环遍历,用low表示对应的低价,用profit代表最后的利润,遍历的过程中不断对这两个变量进行更新即可。
public int maxProfit(int[] prices){ int low = prices[0]; int profit = 0; for(int i = 1; i < prices.length; i++){ low = prices[i] < low ? prices[i] : low; profit = prices[i] - low > profit ? prices[i] - low : profit; } return profit; }
这次通过,时间复杂度为O(n)。
以上是关于[LeetCode] NO. 121 Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 121 Best Time to Buy and Sell Stock
LeetCode OJ 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