leetcode122 Best Time to Buy and Sell Stock II

来源:互联网 发布:mac 重装 u盘 编辑:程序博客网 时间:2024/05/27 20:51

我的leetcode代码在github地址:https://github.com/gaohongbin/leetcode

题目:

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).

Subscribe to see which companies asked this question

翻译:

这个题和leetcode121 Best Time to Buy and Sell Stock差不多,只是leetcode121 Best Time to Buy and Sell Stock只能完成一次交易,而leetcode122 Best Time to Buy and Sell Stock II可以完成多次交易。求出最大的收益。


思路:

这个题刚开始没有思路,在纸上画一画我们可能有点思路了,我自己的思路是这样的。

如果数组是2,4,5,8这种递增的数组,则8-2就是能得到的最大利润。

如果数组为2,5,4,8这种数组,则(5-2)+(8-4)就是得到的最大利润,如果一个数组在递增的过程突然不再递增,则就可以进行一次交易了。

如果数组为4,3,2,5这种数组,则在递减到最低点时买入,在相邻的一个最高点卖出。


根据这个思路,我写下了如下的代码:

代码:

public int maxProfit(int[] prices) {          int length=prices.length;        if(prices==null || length<2)        return 0;                int maxProfit=0;        int price=prices[0];        int lastSellPrice=prices[0];        for(int i=1;i<length;i++){        if(prices[i]>price){            if(prices[i]>lastSellPrice)            lastSellPrice=prices[i];            if(prices[i]<lastSellPrice){            maxProfit+=lastSellPrice-price;            price=prices[i];            lastSellPrice=price;            }        }        if(prices[i]<=price){        if(lastSellPrice>price){        maxProfit+=lastSellPrice-price;            price=prices[i];            lastSellPrice=price;        }        if(lastSellPrice==price){        price=prices[i];        lastSellPrice=price;        }        }        }        maxProfit+=lastSellPrice-price;        return maxProfit;            }

但是最后运行以后才击败了6.2%的代码,发现还有另外一个代码,感觉很精练,最后才发现自己的代码最终实现的也是这样的功能。

public int maxProfit(int[] prices) {        if (prices.length < 2) return 0;                int maxProfit = 0;        for (int i = 1; i < prices.length; i++) {            int diff = prices[i] - prices[i - 1];            if (diff > 0) {                maxProfit += diff;            }        }                return maxProfit;    }




0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 联盟被扣54分怎么办 ofo押金退了余额怎么办 网购还没收货就已签收怎么办 理财公司倒闭分公司法人怎么办 公司让离职不想走怎么办 公司让离职自己不想走怎么办 小孩子有购物狂病怎么办 拉杆箱的轮子卡怎么办 想你了怎么办的英文 那现在怎么办 英文怎写 平安证券账号忘了怎么办 发现发票是假的怎么办 公司收到假发票入账了怎么办 手表皮带有汗味怎么办 利客来购物卡丢了怎么办 乐天玛特倒闭卡怎么办 lv皮带买长了怎么办 密袋鼠咬了人怎么办 lv皮带如果长了怎么办 天赐农场公众号进不去了怎么办 苹果删了订阅号怎么办 蚂蚁借呗没有自动扣款怎么办 有对方qq号名字怎么办 腾讯模拟器刺激现场注册上限怎么办 丹阳智慧人社登入密码忘了怎么办? ipad系统被锁了怎么办 电脑管理员账号删了怎么办 自己电脑删文件需要管理员怎么办 苹果电脑管理员密码忘记了怎么办 电脑提示安全设置不允许下载怎么办 微信和ipad同步怎么办 苹果6空间已满怎么办 苹果6内存虚满怎么办 监控主机密码忘了怎么办 加购物车不下单怎么办 绑定qq账号消息不见了怎么办 现在的注册微信怎么办 爱奇艺手机号码被别人绑定了怎么办 手机号码换了支付宝账号怎么办 qq换手机号了怎么办呢 公司被注销了公众号怎么办