leetcode122.[DP] Best Time to Buy and Sell Stock II
2016-03-24 14:56
369 查看
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). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路:今天价格减去前一天价格,如果为正,则加进sum中
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). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路:今天价格减去前一天价格,如果为正,则加进sum中
import sys MAX_=sys.maxint MIN_=-sys.maxint class Solution(object): def maxProfit(self, prices): if not len(prices): return 0 sum=0 prices.append(MIN_) prices.insert(0,MAX_) flag_pre=-1 flag_last=-1 for i in range(1,len(prices)-1): if flag_pre==-1: if prices[i]<prices[i+1] and prices[i]<=prices[i-1]: flag_pre=prices[i] if flag_pre!=-1: if prices[i]>prices[i+1] and prices[i]>=prices[i-1]: flag_last=prices[i] if flag_pre!=-1 and flag_last!=-1: sum=sum+flag_last-flag_pre flag_pre=-1;flag_last=-1 if flag_pre!=-1 and flag_last!=-1: sum=sum+flag_last-flag_pre return sum
import sys MAX_=sys.maxint class Solution(object): def maxProfit(self, prices): if not len(prices): return 0 sum=0 prices.insert(0,MAX_) for i in range(1,len(prices)): diff=prices[i]-prices[i-1] if diff>=0: sum=sum+diff return sum
相关文章推荐
- 万得股票历史数据接口
- [转]加盐hash保存密码的正确方式
- Mysql用户与权限管理
- android .9.png ”点九” 图片制作方法
- Perl爬取江西失信执行
- 使用Zookeeper实现来监控服务器集群及负载状态
- CrackMapExec:域环境渗透中的瑞士军刀
- 深入了解CSS行高 Line Height属性
- java遍历树(深度遍历和广度遍历
- 1.java精华散记----泛型
- MyAnnotationBeanFactoryPostProcessor
- 零基础准备ocp第一天
- C# 自定义控件 属性个人遇到问题详解 参数无效
- HDOJ 2034 人见人爱A-B
- POJ 3680 Intervals(最小费用流)
- code forces E A rectangle
- lamp
- cmd中如何得到另外一个命令的结果
- linux文件属性与权限的修改
- PAT 乙级 1026. 程序运行时间