leetcode網址
找到最低價購入,並在最高價時售出,購入時間必須在售出前,最後回傳利潤是多少
Input: prices = [7,1,5,3,6,4] Output: 5 Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
用Kadane's algorithm,就可以只用O(N)的時間複雜度
mini
price-mini
profit
走完整個序列,在過程中keep一個值來找出最大差的方式就是Kadane's Algorithm,算是一種DP的方法,可以將 O(N2)的問題降低成O(N)
int maxProfit(vector<int>&prices){ int mini=INT_MAX, profit=0; for(auto&price: prices){ mini = min(price, mini); profit = max(price-mini, profit); } return profit; }
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up