day145-LeetCode 121. 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.

Example 1: Input: [7, 1, 5, 3, 6, 4]

Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2: Input: [7, 6, 4, 3, 1]

Output: 0

In this case, no transaction is done, i.e. max profit = 0.

分析

数组中的元素,从index 0 到最后一位,都表示每天的股价变化。求给出的数组中,利益最大的一天。即,从后往前相减,整数最大的值

题解

function maxProfit (prices) {
// 表示最低的股价,MAX_表示无限大
let min = Number.MAX_SAFE_INTEGER
let maxProfit = 0
for (let i = 0; i < prices.length; i++) {
// 冒泡找出最小值
if (prices[i] < min) {
min = prices[i]
}
// 当前可获利的值
let calProfit = prices[i] - min
if(calProfit > maxProfit) {
maxProfit = calProfit
}
}
return maxProfit
}
文章作者: lmislm
文章链接: http://lmislm.com/2019/06/06/2019-06-07/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog