Skip to content

Commit cc6b937

Browse files
committedMar 12, 2020
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题63. 股票的最大利润
1 parent 2261df2 commit cc6b937

File tree

3 files changed

+89
-0
lines changed

3 files changed

+89
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# [面试题63. 股票的最大利润](https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/)
2+
3+
## 题目描述
4+
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
5+
6+
**示例 1:**
7+
8+
```
9+
输入: [7,1,5,3,6,4]
10+
输出: 5
11+
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
12+
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
13+
```
14+
15+
**示例 2:**
16+
17+
```
18+
输入: [7,6,4,3,1]
19+
输出: 0
20+
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
21+
```
22+
23+
**限制:**
24+
25+
- `0 <= 数组长度 <= 10^5`
26+
27+
## 解法
28+
### Python3
29+
```python
30+
class Solution:
31+
def maxProfit(self, prices: List[int]) -> int:
32+
if len(prices) == 0:
33+
return 0
34+
mi = prices[0]
35+
res = 0
36+
for val in prices[1:]:
37+
res = max(res, val - mi)
38+
mi = min(mi, val)
39+
return res
40+
```
41+
42+
### Java
43+
```java
44+
class Solution {
45+
public int maxProfit(int[] prices) {
46+
int len = prices.length;
47+
if (len == 0) {
48+
return 0;
49+
}
50+
int min = prices[0];
51+
int res = 0;
52+
for (int i = 1; i < len; ++i) {
53+
res = Math.max(res, prices[i] - min);
54+
min = Math.min(min, prices[i]);
55+
}
56+
return res;
57+
}
58+
}
59+
```
60+
61+
### ...
62+
```
63+
64+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
int len = prices.length;
4+
if (len == 0) {
5+
return 0;
6+
}
7+
int min = prices[0];
8+
int res = 0;
9+
for (int i = 1; i < len; ++i) {
10+
res = Math.max(res, prices[i] - min);
11+
min = Math.min(min, prices[i]);
12+
}
13+
return res;
14+
}
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def maxProfit(self, prices: List[int]) -> int:
3+
if len(prices) == 0:
4+
return 0
5+
mi = prices[0]
6+
res = 0
7+
for val in prices[1:]:
8+
res = max(res, val - mi)
9+
mi = min(mi, val)
10+
return res

0 commit comments

Comments
 (0)
Please sign in to comment.