leetcode Best Time to Buy and Sell Stock
2016-06-01 10:48
323 查看
题目
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.
这道题显然是用DP做。
一开始把题目想复杂了,后来发现还是挺简单的,有很多类似的题目,下面给出思路。
设置一个值currentMax,该值记录a[0]-a[k]内,在0-k内买入,k卖出的最大值。
那么currentMax[i+1]=
if(currentMax[i]>0)
currentMax[i]+(a[i+1]-a[i])
else
a[i+1]-a[i]
比如,对于6,1,3,2,4,7
对于6,1,买入卖出肯定是亏损的,此时的max为-5
那么对于6,1,3来说,6,1最大值是负的,那么6,1,3的最大值肯定不包含6,1.因此其最大值为2
对于6,1,3,2,来说,6,3,1的最大值为2,那么最大值为1
依次类推
下面给出代码
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.
这道题显然是用DP做。
一开始把题目想复杂了,后来发现还是挺简单的,有很多类似的题目,下面给出思路。
设置一个值currentMax,该值记录a[0]-a[k]内,在0-k内买入,k卖出的最大值。
那么currentMax[i+1]=
if(currentMax[i]>0)
currentMax[i]+(a[i+1]-a[i])
else
a[i+1]-a[i]
比如,对于6,1,3,2,4,7
对于6,1,买入卖出肯定是亏损的,此时的max为-5
那么对于6,1,3来说,6,1最大值是负的,那么6,1,3的最大值肯定不包含6,1.因此其最大值为2
对于6,1,3,2,来说,6,3,1的最大值为2,那么最大值为1
依次类推
下面给出代码
public class Solution { /** * @param args */ public int maxProfit(int[] prices) { if(prices.length==0||prices.length==1) return 0; int maxEnd=1; int currentMax=0; int max=0; for(int i=1;i<prices.length;i++) { System.out.println("i="+i+",maxEnd="+maxEnd+"max="+max); if(currentMax>0) { currentMax=prices[i]-prices[i-1]+currentMax; } else { currentMax=prices[i]-prices[i-1]; } if(currentMax>max) max=currentMax; } if(max<0) return 0; return max; } public static void main(String[] args) { // TODO Auto-generated method stub int []a={6,1,3,2,4,7}; System.out.println(new Solution().maxProfit(a)); } }
相关文章推荐
- Nginx的SSL配置优化
- Majority Element解决:Moore's Voting Algorithm
- 重新学习《C++Primer5》第12章-动态内存
- 百度霸屏技术的源码发布
- 使用appassembler-maven-plugin插件生成启动脚本
- BP神经网络(地震数据反推测井曲线)
- SELECT DISTINCT
- 将博客搬至51CTO
- 破译实践
- hibernate配置oracle生成序列结果为负数
- Linux5.8下配置web服务器-入门级指导手册(step by step)
- 十四. bash shell的操作环境
- PADS2007库转换为PADS 9.0以上库文件
- Android无需root实现apk的静默安装
- getLocationOnScreen不起作用原因
- How to use git in general and bitbucket in particular
- 摆脱第三方库系列(一)- 自己写一个侧拉菜单
- stl中常用的函数
- java数组自动扩容的方法。
- 初识IOS,Label控件的应用。