Skip to content

Commit

Permalink
Add 191 201 231 342
Browse files Browse the repository at this point in the history
  • Loading branch information
MisterBooo committed May 13, 2019
1 parent ba6b338 commit b0b6a88
Show file tree
Hide file tree
Showing 6 changed files with 373 additions and 220 deletions.
6 changes: 5 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

文章最新首发于微信公众号 **五分钟学算法** ,您可以关注获取最新的文章。

### 汇总
## 汇总

| 序号 | 题目&题解 |
| ---- | ------------------------------------------------------------ |
Expand Down Expand Up @@ -51,11 +51,14 @@
| 167 | [两数之和 II - 输入有序数组](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第167号问题:两数之和II-输入有序数组.md) |
| 172 | [阶乘后的零](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第172号问题:阶乘后的零.md) |
| 187 | [重复的 DNA 序列](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第187号问题:重复的DNA序列.md) |
| 191 | [位1的个数](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第191号问题:位1的个数.md) |
| 199 | [二叉树的右视图](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第199号问题:二叉树的右视图.md) |
| 201 | [数字范围按位与](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第201号问题:数字范围按位与.md) |
| 203 | [移除链表元素](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第203号问题:移除链表元素.md) |
| 206 | [反转链表](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第206号问题:反转链表.md) |
| 209 | [长度最小的子数组](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第209号问题:长度最小的子数组.md) |
| 219 | [存在重复元素 II](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第219号问题:存在重复元素II.md) |
| 231 | [2的幂](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第231号问题:2的幂.md) |
| 237 | [删除链表中的节点](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第237号问题:删除链表中的节点.md) |
| 239 | [滑动窗口最大值](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第239号问题:滑动窗口最大值.md) |
| 279 | [完全平方数](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第279号问题:完全平方数.md) |
Expand All @@ -65,6 +68,7 @@
| 326 | [3 的幂](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第326号问题:3的幂.md) |
| 328 | [奇偶链表](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第328号问题:奇偶链表.md) |
| 344 | [反转字符串](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第344号问题:反转字符串.md) |
| 342 | [4的幂](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第342号问题:4的幂.md) |
| 349 | [两个数组的交集](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第349号问题:两个数组的交集.md) |
| 350 | [两个数组的交集 II](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第350号问题:两个数组的交集II.md) |
| 445 | [两数相加 II](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第445号问题:两数相加II.md) |
Expand Down
242 changes: 23 additions & 219 deletions notes/LeetCode第122号问题:买卖股票的最佳时机II.md
Original file line number Diff line number Diff line change
@@ -1,135 +1,15 @@


# 浅谈什么是动态规划以及相关的「股票」算法题
# LeetCode122号问题:买卖股票的最佳时机II

> 本文首发于公众号「五分钟学算法」,是[图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>)系列文章之一。
>
> 个人网站:[https://www.cxyxiaowu.com](https://www.cxyxiaowu.com)

## 动态规划

### 1 概念

  **动态规划**算法是通过拆分问题,定义问题状态和状态之间的关系,使得问题能够以递推(或者说分治)的方式去解决。在学习动态规划之前需要明确掌握几个重要概念。

  **阶段**:对于个完整的问题过程,适当的切分为若干个相互联系的子问题,每次在求解个子问题,则对应个阶段,整个问题的求解转化为按照阶段次序去求解。

  **状态**:状态表示每个阶段开始时所处的客观条件,即在求解子问题时的已知条件。状态描述了研究的问题过程中的状况。

  **决策**:决策表示当求解过程处于某阶段的某状态时,可以根据当前条件作出不同的选择,从而确定下个阶段的状态,这种选择称为决策。

  **策略**:由所有阶段的决策组成的决策序列称为全过程策略,简称策略。

  **最优策略**:在所有的策略中,找到代价最小,性能最优的策略,此策略称为最优策略。

  **状态转移方程**:状态转移方程是确定两个相邻阶段状态的演变过程,描述了状态之间是如何演变的。

### 2 使用场景

能采用动态规划求解的问题的般要具有 3 个性质:

  (1)**最优化**:如果问题的最优解所包含的子问题的解也是最优的,就称该问题具有最优子结构,即满足最优化原理。子问题的局部最优将导致整个问题的全局最优。换句话说,就是问题的个最优解中定包含子问题的个最优解。

  (2)**无后效性**:即某阶段状态旦确定,就不受这个状态以后决策的影响。也就是说,某状态以后的过程不会影响以前的状态,只与当前状态有关,与其他阶段的状态无关,特别是与未发生的阶段的状态无关。

   (3)**重叠子问题**:即子问题之间是不独立的,个子问题在下阶段决策中可能被多次使用到。(该性质并不是动态规划适用的必要条件,但是如果没有这条性质,动态规划算法同其他算法相比就不具备优势)

### 3 算法流程

  (1)划分阶段:按照问题的时间或者空间特征将问题划分为若干个阶段。
  (2)确定状态以及状态变量:将问题的不同阶段时期的不同状态描述出来。
  (3)确定决策并写出状态转移方程:根据相邻两个阶段的各个状态之间的关系确定决策。
  (4)寻找边界条件:般而言,状态转移方程是递推式,必须有个递推的边界条件。
  (5)设计程序,解决问题

## 实战练习

下面的三道算法题都是来源于 LeetCode 上与股票买卖相关的问题 ,我们按照 **动态规划** 的算法流程来处理该类问题。

**股票买卖**这类的问题,都是给个输入数组,里面的每个元素表示的是每天的股价,并且你只能持有支股票(也就是你必须在再次购买前出售掉之前的股票),般来说有下面几种问法:

- 只能买卖
- 可以买卖无数次
- 可以买卖 k

需要你设计个算法去获取最大的利润。

## 买卖股票的最佳时机

题目来源于 LeetCode 上第 121 号问题:买卖股票的最佳时机。题目难度为 Easy,目前通过率为 49.4% 。
在之前有关 [**动态规划与股票问题文**](https://github.com/MisterBooo/LeetCodeAnimation/tree/master/notes/LeetCode第122号问题:买卖股票的最佳时机II.md) 中,小吴使用了动态规划的思想进行了分析和写套路代码,但还是有一些小伙伴不是很明白,今天重新拿出一题从另外一个角度进行分析,希望能帮助大家更容易理解。

### 题目描述

给定个数组,它的第 *i* 个元素是支给定股票第 *i* 天的价格。

如果你最多只允许完成笔交易(即买入和卖出支股票),设计个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

**示例 1:**

```
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
```

**示例 2:**

```
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0
```

### 题目解析

我们按照动态规划的思想来思考这道问题。

#### 状态

有 **买入(buy)** 和 **卖出(sell)** 这两种状态。

#### 转移方程

对于买来说,买之后可以卖出(进入卖状态),也可以不再进行股票交易(保持买状态)。

对于卖来说,卖出股票后不在进行股票交易(还在卖状态)。

只有在手上的钱才算钱,手上的钱购买当天的股票后相当于亏损。也就是说当天买的话意味着损失`-prices[i]`,当天卖的话意味着增加`prices[i]`,当天卖出总的收益就是 `buy+prices[i]` 。

所以我们只要考虑当天买和之前买哪个收益更高,当天卖和之前卖哪个收益更高。

- buy = max(buy, -price[i]) (注意:根据定义 buy 是负数)
- sell = max(sell, prices[i] + buy)

#### 边界

天 `buy = -prices[0]`, `sell = 0`,最后返回 sell 即可。

### 代码实现

```java
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1)
return 0;
int buy = -prices[0], sell = 0;
for(int i = 1; i < prices.length; i++) {
buy = Math.max(buy, -prices[i]);
sell = Math.max(sell, prices[i] + buy);

}
return sell;
}
}
```



## 买卖股票的最佳时机 II

题目来源于 LeetCode 上第 122 号问题:买卖股票的最佳时机 II。题目难度为 Easy,目前通过率为 53.0% 。

### 题目描述
Expand Down Expand Up @@ -169,126 +49,50 @@ class Solution {

### 题目解析

#### 状态

有 **买入(buy)** 和 **卖出(sell)** 这两种状态。

#### 转移方程

对比上题,这里可以有无限次的买入和卖出,也就是说 **买入** 状态之前可拥有 **卖出** 状态,所以买入的转移方程需要变化。

- buy = max(buy, sell - price[i])
- sell = max(sell, buy + prices[i] )

#### 边界

天 `buy = -prices[0]`, `sell = 0`,最后返回 sell 即可。

### 代码实现

```java
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1)
return 0;
int buy = -prices[0], sell = 0;
for(int i = 1; i < prices.length; i++) {
sell = Math.max(sell, prices[i] + buy);
buy = Math.max( buy,sell - prices[i]);
}
return sell;
}
}
```


我们从实际场景去思考,假设你处于股票市场,你想获得最大收益的话理想操作是什么?

## 买卖股票的最佳时机 III
当然是 **低点买入,高点卖出** !

题目来源于 LeetCode 上第 123 号问题:买卖股票的最佳时机 III。题目难度为 Hard,目前通过率为 36.1%
举个简单的数组为例 [10012081],肉眼扫过去,第二天买第四天卖的话收益最高( 81 - 1) = 80

### 题目描述

给定个数组,它的第 *i* 个元素是支给定的股票在第 *i* 天的价格。

设计个算法来计算你所能获取的最大利润。你最多可以完成 *两笔* 交易。

**注意:** 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

**示例 1:**

```
输入: [3,3,5,0,0,3,1,4]
输出: 6
解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3
随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3
```

**示例 2:**

```
输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4
注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
```

**示例 3:**

```
输入: [7,6,4,3,1]
输出: 0
解释: 在这个情况下, 没有交易完成, 所以最大利润为 0
```

### 题目解析

这里限制了最多两笔交易。
那为什么可以知道在第四天卖而不在第三天卖呢?

#### 状态
实际上,注意题目是没有限制买卖交易次数的,完全可以在第三天卖出去,只不过发现第四天有涨了,那么就在第三天再买回来。

有 **第次买入(fstBuy)** 、 **第次卖出(fstSell)**、**第二次买入(secBuy)** 和 **第二次卖出(secSell)** 这四种状态
即 ` (81 - 1) = [( 20 - 1 ) + ( 81 - 20 )]`

#### 转移方程
也就是说,第二天买、第三天卖,第三天买、第四天卖这四个动作与第二天买、第四天卖结果是致的。

这里最多两次买入和两次卖出,也就是说 **买入** 状态之前可拥有 **卖出** 状态,**卖出** 状态之前可拥有 **买入** 状态,所以买入和卖出的转移方程都需要变化。
**所以只需要今天的价格比昨天更高,就卖出**!(反正可以再买入)

- fstBuy = max(fstBuy , -price[i])
- fstSell = max(fstSellfstBuy + prices[i] )
- secBuy = max(secBuyfstSell -price[i]) (受第次卖出状态的影响)
- secSell = max(secSellsecBuy + prices[i] )
总结下就是:从第二天开始观察,如果当前价格(今天)比之前价格(昨天)高,则把差值加入到利润中(因为我们可以昨天买入,今天卖出,如果明天价位更高的话,还可以今天买入,明天再抛出)。以此类推,遍历完整个数组后即可求得最大利润。

#### 边界
### 图片描述

- 开始 `fstBuy = -prices[0]`
- 买入后直接卖出,`fstSell = 0`
- 买入后再卖出再买入,`secBuy - prices[0]`
- 买入后再卖出再买入再卖出,`secSell = 0`

最后返回 secSell
![买卖股票的最佳时机 II](https://upload-images.jianshu.io/upload_images/1940317-07904ca85dc535a9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

### 代码实现

```java
//程序员小吴
class Solution {
public int maxProfit(int[] prices) {
int fstBuy = Integer.MIN_VALUE, fstSell = 0;
int secBuy = Integer.MIN_VALUE, secSell = 0;
for(int i = 0; i < prices.length; i++) {
fstBuy = Math.max(fstBuy, -prices[i]);
fstSell = Math.max(fstSell, fstBuy + prices[i]);
secBuy = Math.max(secBuy, fstSell - prices[i]);
secSell = Math.max(secSell, secBuy + prices[i]);
int profit = 0;
for (int i = 1 ; i < prices.length; i++){
if (prices[i] > prices[i-1]){
profit = profit + prices[i] - prices[i - 1];
}
}
return secSell;

return profit;
}
}
```





![](https://bucket-1257126549.cos.ap-guangzhou.myqcloud.com/blog/fz0rq.png)


Expand Down
Loading

0 comments on commit b0b6a88

Please sign in to comment.