码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-06-19 01:18:15      阅读:150      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!