题目描述:

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.

解题思路:

动态规划,记录最小值的那个值

代码如下:

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0 maxProfit = 0
minPrice = prices[0] for i in range(len(prices)):
if prices[i] < minPrice:
minPrice = prices[i]
if prices[i] - minPrice > maxProfit:
maxProfit = prices[i] - minPrice return maxProfit

  

最新文章

  1. Git系列教程二 基础介绍
  2. LightOJ1051 Good or Bad(DP)
  3. sass初步认识1
  4. java提高篇---HashTable
  5. [置顶] DataGridView控件---绑定数据方法
  6. CentOS7设置IP地址
  7. Oracle SYS_CONTEXT Function
  8. Android 安全测试
  9. poj3258 二分 最小值最大化问题
  10. php实现备份数据库
  11. 根据id查询所有子节点/父节点,mysql 以及ssm前后台处理流程
  12. Linux eclipse 编译C++
  13. Away3D引擎学习入门笔记
  14. java并发:CopyOnWriteArrayList简单理解
  15. hive元数据研究
  16. C# Http访问帮助类,支持get post请求文件下载 [
  17. 项目管理工具- Maven
  18. UI1
  19. Android Studio -导入项目 gradle处理
  20. C#中Console.ReadLine()和Console.Read()有何区别?

热门文章

  1. 关于javascript获取页面高度宽度
  2. 如何查看eclipse中servlet跟jsp的版本
  3. linux下tomcat下部署项目如何打包压缩备份
  4. 多线程包:java.util.concurrent,
  5. Axure 注册码
  6. Qt之获取本机网络信息(MAC, IP等等,很全)
  7. Android 消息广播Intent传递数据
  8. SpringBoot配置属性之Server
  9. Redhat6下安装QEMU
  10. 很实用的js限制不让输入其他字符,只让输入数字和 js生成UUID