[LeetCode][JavaScript]Best Time to Buy and Sell Stock
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 };