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

121. Best Time to Buy and Sell Stock

时间:2016-06-15 06:58:38      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

顺着数组走,保存:

1.到目前为止最大profit

2.到目前为止最小price

更新两个数据,结尾返回maxProfit

 1    public int maxProfit(int[] prices) {
 2         if(prices.length < 1) {
 3             return 0;
 4         }
 5         int minPrice = prices[0];
 6         int maxProfit = 0;
 7         for(int i = 1; i < prices.length; i++) {
 8             minPrice = (prices[i] < minPrice)? prices[i]: minPrice;
 9             maxProfit = (maxProfit < prices[i] - minPrice)? prices[i] - minPrice: maxProfit;
10         }
11         return maxProfit;
12     }

 

121. Best Time to Buy and Sell Stock

标签:

原文地址:http://www.cnblogs.com/warmland/p/5586103.html

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