博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - 121. Best time to buy and sell stock
阅读量:5083 次
发布时间:2019-06-13

本文共 1725 字,大约阅读时间需要 5 分钟。

 
 

Description

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

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

Output: 0

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

Solution

A了题目之后,这一题思路就比较清晰了,相信各位看官稍动脑筋应该也能想到,或者看代码进行分析。

当然,特别要注意列表为空的情况(此时应返回0!)

python

1 class Solution(object): 2     def maxProfit(self, prices): 3         """ 4         :type prices: List[int] 5         :rtype: int 6         """ 7         if len(prices) == 0: 8             return 0 9 10         max_diff = 011         cur_diff = 012         buy_price = prices[0]13         for item in prices[1:]:14             if item < buy_price:15                 buy_price = item16                 cur_diff = 017             else:18                 cur_diff = item - buy_price19                 max_diff = max(max_diff, cur_diff)20 21         return max_diff

 

cpp

1 class Solution { 2 public: 3     int maxProfit(vector
& prices) { 4 if (prices.size()==0) 5 return 0; 6 7 int buy_price = prices.at(0); 8 int max_diff = 0; 9 int cur_diff = 0;10 int temp = 0;11 for (size_t i=1; i
< cur_diff ? cur_diff : max_diff);22 }23 }24 25 return max_diff;26 }27 };

 

 
 

转载于:https://www.cnblogs.com/gxcdream/p/7507404.html

你可能感兴趣的文章
周一01.1编程与编程语言
查看>>
在Mac OS X 10.9上安装 Thrift 0.9.1
查看>>
aide入侵检测工具与crontab
查看>>
Web开发技术——HTML基础
查看>>
《Windows驱动开发技术详解》之Windows内存管理
查看>>
Linux 关于SELinux的命令及使用
查看>>
近年来CVPR,ICCV论文列表
查看>>
C#.NET 大型企业信息化系统集成快速开发平台 4.2 版本 – 员工离职管理
查看>>
统计学 nested_design 嵌套设计
查看>>
javascript基础知识(26) 闭包
查看>>
iOS--雪花掉落特效
查看>>
Java面向对象2(G~J)
查看>>
Java int 与 Integer 区别
查看>>
Cenots7下安装运行.NET Core、MicroSoft SQL Server 2019 preview 的基础实践
查看>>
第二阶段个人冲刺05
查看>>
coffee 编译时, 用本地环境
查看>>
jzoj 6271. 2019.8.4【NOIP提高组A】锻造 (forging)
查看>>
Java面向对象和特征
查看>>
【算法与数据结构实战】线性表操作-实现A并B,结果放入A中
查看>>
20141225 数组二
查看>>