[leetCode刷题笔记]2017.02.18
来源:互联网 发布:大数据用什么软件 编辑:程序博客网 时间:2024/06/06 06:41
121. Best Time to Buy and Sell Stock
动态规划,保存最小值,再找出对应的最大profit
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
# min price and max profit
minPrice = prices[0]
maxProfit = 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
122. Best Time to Buy and Sell Stock II
贪心算法,碰到prices[i +1] > prices[i]情况就卖掉,注意边界情况。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices is None or len(prices) < 2:
return 0
buy = 0
sell = 0
profit = 0
for i in range(len(prices) - 1):
if (prices[i + 1] >= prices[i]):
sell = i + 1
else:
profit = profit + (prices[sell] - prices[buy])
buy = i + 1
sell = i + 1
return profit + max(0, (prices[sell] - prices[buy]))
123. Best Time to Buy and Sell Stock III
有点难的题目,根据i的位置,动态将数组分成两个部分,并用p1存贮i之前的最大利润p2存储i之后的最大利润。最后求p1[i] + p2[i]的最大值。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n <= 1:
return 0
# generate two arrays
# max profit before i
p1 = [0] * n
# max profit after i
p2 = [0] * n
minV = prices[0]
for i in range(1, n):
minV = min(minV, prices[i])
p1[i] = max(p1[i - 1], prices[i] - minV)
maxV = prices[-1]
for i in range(n -2, -1, -1):
maxV = max(maxV, prices[i])
p2[i] = max(p2[i +1], maxV - prices[i])
result = 0
for i in range(n):
result = max(result, p1[i] + p2[i])
return result
217. Contains Duplicate
用一个map,每循环一个,看map里面有没有,有的话false没有的话加入map
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
map = {}
for i in nums:
if i in map:
return True
map[i] = True
return False
- [leetCode刷题笔记]2017.02.18
- Leetcode刷题笔记
- LeetCode刷题笔记
- LeetCode刷题笔记
- leetcode刷题笔记
- [leetCode刷题笔记]2017.02.01
- [leetCode刷题笔记]2017.02.02
- [leetCode刷题笔记]2017.02.03
- [leetCode刷题笔记]2017.02.04
- [leetCode刷题笔记]2017.02.05
- [leetCode刷题笔记]2017.02.06
- [leetCode刷题笔记]2017.02.07
- [leetCode刷题笔记]2017.02.08
- [leetCode刷题笔记]2017.02.09
- [leetCode刷题笔记]2017.02.11
- [leetCode刷题笔记]2017.02.12
- [leetCode刷题笔记]2017.02.13
- [leetCode刷题笔记]2017.02.14
- tomcat Content-Language:en-US 导致乱码
- 职场技巧之PPT制作
- ubuntu 下安装VM12
- Android面试题(2)
- (学习总结)鸟哥基础篇第三版:第二十章
- [leetCode刷题笔记]2017.02.18
- 菜狗的C++ primer读书笔记:第二章 变量和基本类型
- 拓扑结构相同子树练习题
- BZOJ3514: Codechef MARCH14 GERALD07加强版
- css垂直居中的六种方法
- Codeforces 767A Snacktower
- python位运算纪录
- 746B Decoding
- asp.net core mvc剖析:KestrelServer