1. 程式人生 > >121.Best Time to Buy and Sell Stock

121.Best Time to Buy and Sell Stock

ges 9.png img ++ https des clas tps urn

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

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

技術分享

法一(超時):直接兩個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

法二(借鑒):貪心,一次遍歷,從數組最左端開始找相對較小的數,然後

技術分享
 1         int min = Integer.MAX_VALUE;
 2         int res = 0;
 3         for(int i = 0; i < prices.length; i++) {
 4             if(prices[i] < min) {
 5                 min = prices[i];
 6             }
 7             else if(prices[i] - min > res){
 8                 res = prices[i] - min;
9 } 10 } 11 return res;
View Code

121.Best Time to Buy and Sell Stock