Skip to content

Commit 2ef92ec

Browse files
committed
add 122
1 parent 2c3ae8a commit 2ef92ec

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
| :--- | :------------------------------------------ |
1818
| 26 | [Remove Duplicates from Sorted Array][026] |
1919
| 121 | [Best Time to Buy and Sell Stock][121] |
20-
| 122 | Best Time to Buy and Sell Stock II |
20+
| 122 | [Best Time to Buy and Sell Stock II][122] |
2121
| 189 | Rotate Array |
2222

2323

@@ -28,3 +28,4 @@
2828

2929
[026]: https://github.com/andavid/leetcode-java/blob/master/note/026/README.md
3030
[121]: https://github.com/andavid/leetcode-java/blob/master/note/121/README.md
31+
[122]: https://github.com/andavid/leetcode-java/blob/master/note/122/README.md

note/122/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# [Best Time to Buy and Sell Stock II][title]
2+
3+
## Description
4+
5+
Say you have an array for which the *i*<sup>th</sup> element is the price of a given stock on day *i*.
6+
7+
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).
8+
9+
## 思路
10+
题意是给出一个数组代表每天的股票金额,在每天只能买或卖的情况下求出收益最高值,可以进行多次买卖交易,但是必须先卖掉才能再买。
11+
12+
只需要把所有相邻递增的值都加起来即可。
13+
14+
## [完整代码][src]
15+
16+
```java
17+
class Solution {
18+
public int maxProfit(int[] prices) {
19+
int maxProfit = 0;
20+
int len = prices.length;
21+
for (int i = 1; i < len; i++) {
22+
if (prices[i] > prices[i - 1]) {
23+
maxProfit += prices[i] - prices[i - 1];
24+
}
25+
}
26+
return maxProfit;
27+
}
28+
}
29+
```
30+
31+
[title]: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii
32+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_122/Solution.java
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.andavid.leetcode._122;
2+
3+
public class Solution {
4+
public int maxProfit(int[] prices) {
5+
int maxProfit = 0;
6+
int len = prices.length;
7+
for (int i = 1; i < len; i++) {
8+
if (prices[i] > prices[i - 1]) {
9+
maxProfit += prices[i] - prices[i - 1];
10+
}
11+
}
12+
return maxProfit;
13+
}
14+
15+
public static void main(String[] args) {
16+
Solution solution = new Solution();
17+
System.out.println(solution.maxProfit(new int[]{7, 1, 5, 3, 6, 4}));
18+
System.out.println(solution.maxProfit(new int[]{7, 6, 4, 3, 1}));
19+
}
20+
}

0 commit comments

Comments
 (0)