zoukankan      html  css  js  c++  java
  • [leetcode]Best Time to Buy and Sell Stock @ Python

    原题地址:https://oj.leetcode.com/problems/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.

    解题思路:扫描一遍数组,使用low来标记最低价位,如果有更低的价位,置换掉。

    代码:

    class Solution:
        # @param prices, a list of integer
        # @return an integer
        def maxProfit(self, prices):
            if len(prices) <= 1: return 0
            low = prices[0]
            maxprofit = 0
            for i in range(len(prices)):
                if prices[i] < low: low = prices[i]
                maxprofit = max(maxprofit, prices[i] - low)
            return maxprofit
  • 相关阅读:
    FR #3题解
    L3-005. 垃圾箱分布
    L2-004. 这是二叉搜索树吗?
    L2-002. 链表去重
    L1-009. N个数求和
    L3-003. 社交集群
    L3-004. 肿瘤诊断
    L2-001. 紧急救援
    L3-002. 堆栈
    L2-007. 家庭房产
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3765934.html
Copyright © 2011-2022 走看看