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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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 Explanation: In this case, no transaction is done, i.e. max profit = 0.
意思是求差价的最大,一开始想先遍历找一个最小的element,然后再遍历用后面的减去这个element求最大值。
但是这样是错的,因为element并不一定是最小的创造最大profit,比如[2,4,1],所以要换个思路。
总是会over think题目,也不知道为什么,明明很简单一道题,我总是复杂化。
解:
用一个变量来存放便利当中小的元素,然后总是取计算后的利润和当前利润的较大值即可。
class Solution { public int maxProfit(int[] prices) { int buy = Integer.MAX_VALUE, res = 0; for(int price : prices){ buy = Math.min(buy , price); res = Math.max(res , price - buy); } return res; } }
其他地方看到,这其实是一种DP算法的应用
阿西,二刷首先想到的还是最开始的方法。
答案其实要我们既保留每次循环时最小的price(购入价),同时也要计算当前能产生的最大利润。