121.Best Time to Buy and Sell Stock---dp

題目連接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/數組

題目大意:給出一串數組,找到差值最大的差值是多少,要求只能用下標大的減下標小的,例子以下圖:ide

法一(超時):直接兩個for循環,進行一一比較,找出差值最大的點,可是超時了,因此這裏後臺應該規定的是1m的時間,而在1m的時間限制下,複雜度只有10^7左右,或者說不到10^8,這個題的有一個測試用例就超過了一萬的數組大小,因此超時,代碼以下:測試

 1                 int max = 0;
 2         int length = prices.length;
 3         for(int i = length - 1; i > 0; i--) {
 4             for(int j = i - 1; j >= 0; j--) {
 5                 if(max < (prices[i] - prices[j])) {
 6                     max = prices[i] - prices[j];
 7                 }
 8             }
 9         }
10         return max;    
View Code

法二(借鑑):貪心,一次遍歷,從數組最左端開始每次都找相對較小的買入價,而後更新買入價,再找相對較大的賣出價,而後更新利潤,代碼以下:spa

 1         int min = Integer.MAX_VALUE;
 2         int res = 0;
 3         //第i天的價格能夠看做買入價,也能夠看做賣出價
 4         for(int i = 0; i < prices.length; i++) {
 5             //找到更低的買入價
 6             if(prices[i] < min) {
 7                 //更新買入價
 8                 min = prices[i];
 9             }
10             else if(prices[i] - min > res){
11                 //更新利潤
12                 res = prices[i] - min;
13             }
14         }
15         return res;
View Code
相關文章
相關標籤/搜索