leetcode 121 309
来源:互联网 发布:网络运营主管招聘 编辑:程序博客网 时间:2024/06/05 02:38
比较简单的俩个题,第一题O(n)的复杂度,第二题也想用O(n)的复杂度解决,刚开始出错了,直接用DP,毕竟最爱,虽然是O(n2)的复杂度,运行时间排名yefeichan
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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ max_profile=0 if len(prices)==0: return max_profile min_price=prices[0] max_price=prices[0] for i in range(1,len(prices)): if prices[i]>max_price: if max_profile<(prices[i]-min_price): max_profile=prices[i]-min_price max_price=prices[i] if prices[i]<min_price: min_price=prices[i] max_price=prices[i] return max_profile
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]maxProfit = 3transactions = [buy, sell, cooldown, buy, sell]
class Solution(object): def maxProfit(self, prices): max_profile=[0]*(len(prices)+2) if len(prices)<2: return 0 for i in range(len(prices)-1,-1,-1): maxp=max_profile[i+1] for j in range(i+1,len(prices)): if prices[j]>prices[i]: if prices[j]-prices[i]+max_profile[j+2]>maxp: maxp=prices[j]-prices[i]+max_profile[j+2] max_profile[i]=maxp return max_profile[0]
阅读全文
0 0
- leetcode 121 309
- leetcode-121
- leetcode 121
- leetcode 121
- leetcode-121
- Leetcode 121
- leetcode #121 in cpp
- leetCode练习(121)
- [Leetcode] 121, 122, 3
- week14-leetcode #121-BestTimetoBuyandSellStock
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- PAT 乙级 1076. Wifi密码 (15)
- ClassLoader工作机制
- 【SVN】项目清除SVN标记
- SpringMVC中拦截器的使用
- ListView源码解析
- leetcode 121 309
- 设计模式在 TypeScript 中的应用
- redis之如何配置jedisPool参数
- C++笔记——io流条件状态
- 设计模式在 TypeScript 中的应用
- python实现某网站的音乐下载
- PAT乙级 1077. 互评成绩计算 (20)
- SpringMVC框架学习笔记
- StrokesPlus键盘按键表示