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

题目链接: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         //第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
原文地址:https://www.cnblogs.com/cing/p/7701364.html