首页 > 编程语言 > 详细

[LeetCode][JavaScript]Best Time to Buy and Sell Stock

时间:2015-06-19 01:16:18      阅读:323      评论:0      收藏:0      [点我收藏+]

Best Time to Buy and Sell Stock 

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

 

 

 


 

 

 

一图流解释,最低买进最高卖出。

技术分享

 1 /**
 2  * @param {number[]} prices
 3  * @return {number}
 4  */
 5 var maxProfit = function(prices) {
 6     var min = Infinity;
 7     var res = -Infinity;
 8     for(var i = 0; i < prices.length; i++){
 9         if(prices[i] < min){
10             min = prices[i];
11         }
12         if(prices[i] > min && prices[i] - min > res){
13             res = prices[i] - min;
14         }
15     }
16     if(isFinite(res)){
17         return res;
18     }else{
19         return 0;
20     }
21 };

 

[LeetCode][JavaScript]Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/Liok3187/p/4587406.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!