Skip to content

Commit 2f2bc61

Browse files
committed
feat: add 121
1 parent ce29350 commit 2f2bc61

File tree

3 files changed

+60
-1
lines changed

3 files changed

+60
-1
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
|112|[Path Sum][112]|Tree, Depth-first Search|
3939
|118|[Pascal's Triangle][118]|Array|
4040
|119|[Pascal's Triangle II][119]|Array|
41+
|121|[Best Time to Buy and Sell Stock][121]|Array, Dynamic Programmin|
4142

4243

4344
## Medium
@@ -91,6 +92,7 @@
9192
[112]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/112/README.md
9293
[118]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/118/README.md
9394
[119]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/119/README.md
95+
[121]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/121/README.md
9496

9597
[008]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/008/README.md
9698
[019]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/019/README.md

note/119/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
## Description
44

5-
Given an index *k*, return the *k*th row of the Pascal's triangle.
5+
Given an index *k*, return the *k*<sup>th</sup> row of the Pascal's triangle.
66

77
For example, given *k* = 3,
88
Return `[1,3,3,1]`.

note/121/README.md

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# [Best Time to Buy and Sell Stock][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+
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
8+
9+
**Example 1:**
10+
11+
```
12+
Input: [7, 1, 5, 3, 6, 4]
13+
Output: 5
14+
15+
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
16+
17+
```
18+
19+
**Example 2:**
20+
21+
```
22+
Input: [7, 6, 4, 3, 1]
23+
Output: 0
24+
25+
In this case, no transaction is done, i.e. max profit = 0.
26+
```
27+
28+
**Tags:** Array, Dynamic Programmin
29+
30+
31+
## 思路
32+
33+
题意是给出一个数组代表每天的股票金额,让你在最多买卖一次的情况下算出最大的收益额,最简单的就是模拟即可,每次记录当前值减去最小值的差值,与上一次的进行比较然后更新最大值即可。
34+
35+
``` java
36+
class Solution {
37+
public int maxProfit(int[] prices) {
38+
int max = 0, minPrice = Integer.MAX_VALUE;
39+
for (int i = 0; i < prices.length; ++i) {
40+
if (prices[i] < minPrice) minPrice = prices[i];
41+
int delta = prices[i] - minPrice;
42+
if (delta > max) max = delta;
43+
}
44+
return max;
45+
}
46+
}
47+
```
48+
49+
50+
## 结语
51+
52+
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl]
53+
54+
55+
56+
[title]: https://leetcode.com/problems/best-time-to-buy-and-sell-stock
57+
[ajl]: https://github.com/Blankj/awesome-java-leetcode

0 commit comments

Comments
 (0)