Lintcode150 Best Time to Buy and Sell Stock II solution 题解

来源:互联网 发布:mamp mysql 启动失败 编辑:程序博客网 时间:2024/05/19 05:40

【题目描述】

Say you have an array for which theith 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).

假设有一个数组,它的第i个元素是一个给定的股票在第i天的价格。设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。

【题目链接】

www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock-ii/

【题目解析】

卖股票系列之二,允许进行多次交易,但是不允许同时进行多笔交易。直觉上我们可以找到连续的多对波谷波峰,在波谷买入,波峰卖出,稳赚不赔~。那么这样是否比只在一个差值最大的波谷波峰处交易赚的多呢?即比上题的方案赚的多。简单的证明可先假设存在一单调上升区间,若人为改变单调区间使得区间内存在不少于一对波谷波峰,那么可以得到进行两次交易的差值之和比单次交易大,证毕。

计算所有连续波谷波峰的差值之和。需要遍历求得所有波谷波峰的值吗?其实可以把数组看成时间序列,只需要计算相邻序列的差值即可,只累加大于0的差值。

【参考答案】

www.jiuzhang.com/solutions/best-time-to-buy-and-sell-stock-ii/

阅读全文
0 0
原创粉丝点击