题目连结:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
题目:求得答案是利润最高值,不是求哪一天。
整理
# @param {Integer[]} prices
# @return {Integer}
def max_profit(prices)
end
puts max_profit([7, 1, 5, 3, 6, 4]) #=>5
puts max_profit([7, 6, 4, 3, 1]) #=>0
每一天的价钱都有可能是最适合的最低买进与最高卖出。
prices[0] ~ prices[prices.size - 1]
最高价差发生在,当天价钱减去比当天之前的最低价钱中。
def max_profit(prices)
#买进 => 找到最低的保留住
#卖出 => 当天价格 = 卖出
#价差 => 找到最高的保留
#回圈
end
#最低价 = 回圈中每次的值与预设的最低值相比
min_price = [min_price, prices[0..prices.size-1].min
#最高价 = 当天卖价与预设最小买价的差。
max_profit = [max_profit, (prices[0..prices.size-1] - min)].max
整理
# @param {Integer[]} prices
# @return {Integer}
def max_profit(prices)
min_price = prices[0] #买价在array中,所以不可能预设指向0。
max_profit = 0 #检验完都是负数,那就是0,所以一开始设定0。
for i in 0..(prices.size-1)
min_price = [min_price, prices[i]].min
max_profit = [max_profit, (prices[i] - min_price)].max
end
max_profit
end
# @param {Integer[]} prices
# @return {Integer}
def max_profit(prices)
min_price = prices[0]
max_profit = 0
prices.each do |price|
min_price = price if price < min_price
#min_price = [min_price, price].min
max_profit = [max_profit, price - min_price].max
end
max_profit
end
挑自己看得懂的最重要,不过Ruby请选each。
<<: 列举子目录所有档案Python os.walk + filter
什麽是暂存器 register? 暂存器顾名思义就是可以存放资料的地方,那也就是记忆体的一种罗? 记...
Python 内建的数值类函式 数值类函式 执行结果 功能 abs(-10) 10 取绝对值 min...
本来是这麽打算的啦 但翻了一下文件(iOS, Android) 应该是跟以前打包方式差不多 顶多就是...
如果你是熟悉RPG Maker的人 一定知道各式各样实作敌人的方式 其中当然包括使用引擎内建的UI来...
紧张紧张,刺激刺激,从去年下半年才参加UI/UX设计班的菜逼八,今年居然就自不量力的参加传说中的铁人...