剑指offer 面试题63. 股票的最大利润

Amber ·
更新时间:2024-09-21
· 850 次阅读

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
 

限制:

0 <= 数组长度 <= 10^5

如果不加中间那个判断,是没法过用时的,所以突然想起的限制条件让我过了这道题,方法很普通,二重循环 

class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ maxnum = 0 minnum = 0 for i in range(len(prices)): if prices[i]prices[j]): minnum = prices[j] profit = prices[i]-prices[j] maxnum = max(maxnum,profit) return maxnum
作者:cold星辰



面试题 面试 剑指offer 利润 offer 股票

需要 登录 后方可回复, 如果你还没有账号请 注册新账号