FTPrep, 121 Best Time to Buy and Sell Stock
来源:互联网 发布:淘宝手机店 编辑:程序博客网 时间:2024/06/05 20:07
这道题,我想得比较细,也就是把优化的步骤都想好了。另外一些解法是套路模版,就是local 和 global两个变量来进行 不断交互比较。所以没有忽略一些可以忽略的情况。哪种模版的情况再处理复杂问题,即可以优化的情况不是很明显的题型时还是比较powerful的。
和下一道题目对比的话,这里只限买卖一次,下一道是买卖多次,多次的话就是 逢低就卖,再一这个低价买入,交易就发生在低价出现之前。有了这个high level的逻辑,代码就好写了。
代码如下:
class Solution { public int maxProfit(int[] prices) { int len=prices.length; if(len==0) return 0; int profit=0; int low=prices[0]; int high=prices[0]; for(int day=0; day<len; day++){ if(prices[day]<low){ low=prices[day]; high=prices[day]; } else if(prices[day]>high){ high=prices[day]; profit=Math.max(profit,high-low); } } return profit; }}// 相比之前的代码,我这个快多了,代码更多但是判断的条件更加明确,而不是没遇到一个elem就要进行min和max的更新。// 就把把这array想象成股票价格图中的bar,无非就是找到从左到右方向上的 最小值 到 最大值的 差距。// 而且题意给得很清楚,最小值就是0,当天买卖,所以min和max就都可以 从第一天的开始。// 如果比high高,才有必要update:high & profit,在low和high之间,没有必要update。// 如果比low低,那么就要update low,同时以为着之前的low所对应的最大profit已经终结。之后判断的都是以新的low为基准来进行的比较。high也更新了,然后profit不用更新。// 总结一下,前几次提交的code,看看现在的思路为什么又快又好。
阅读全文
0 0
- FTPrep, 121 Best Time to Buy and Sell Stock
- FTPrep, 122 Best Time to Buy and Sell Stock II
- FTPrep, 123 Best Time to Buy and Sell Stock III, 没完全懂,TODO
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 【注意】Java序列化serialVersionUID问题
- FTPrep, 119 Pascal's Triangle II
- Volatile关键字与线程安全
- FTPrep: 120 Triangle,可以归为 pathSum 路径和的这类题,因为用到了list/array,就是一道DP题。
- CI框架部署到nginx环境中后,报404错误(解决方法)
- FTPrep, 121 Best Time to Buy and Sell Stock
- WebSocket与Tomcat兼容问题
- Room架构详解
- 【小坑】Struts注意的几点
- 【工具】使用反射为类快速生成toString方法
- HTTP协议详解(真的很经典)
- 从事Android开发俩年来的经历和感悟
- Unity获取安卓设备唯一识别码
- Quartz-SimpleTrigger解读