码迷,mamicode.com
首页 > 其他好文 > 详细

121.Best Time to Buy and Sell Stock

时间:2017-10-20 21:34:36      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:blank   return   相对   des   最大   大小   .com   gif   超过   

题目链接: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

标签:blank   return   相对   des   最大   大小   .com   gif   超过   

原文地址:http://www.cnblogs.com/cing/p/7701364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!