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
相关文章
相关标签/搜索