Skip to content

Commit 6a8727f

Browse files
authored
feat(ml): $121.best-time-to-buy-and-sell-stock.md (azl397985856#413)
添加Java语言支持,微调语言顺序
1 parent b16913b commit 6a8727f

File tree

1 file changed

+31
-21
lines changed

1 file changed

+31
-21
lines changed

problems/121.best-time-to-buy-and-sell-stock.md

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ Explanation: In this case, no transaction is done, i.e. max profit = 0.
4444

4545
## 代码
4646

47-
语言支持:JS,Python,C++
47+
语言支持:JS,C++,Java,Python
4848

4949
JS Code:
5050

@@ -69,26 +69,6 @@ var maxProfit = function(prices) {
6969
};
7070
```
7171

72-
73-
74-
Python Code:
75-
76-
```python
77-
class Solution:
78-
def maxProfit(self, prices: 'List[int]') -> int:
79-
if not prices: return 0
80-
81-
min_price = float('inf')
82-
max_profit = 0
83-
84-
for price in prices:
85-
if price < min_price:
86-
min_price = price
87-
elif max_profit < price - min_price:
88-
max_profit = price - min_price
89-
return max_profit
90-
```
91-
9272
C++ Code:
9373
```c++
9474
/**
@@ -111,8 +91,38 @@ public:
11191
}
11292
};
11393
```
94+
Java Code:
95+
```java
96+
class Solution {
97+
public int maxProfit(int[] prices) {
98+
int minprice = Integer.MAX_VALUE;
99+
int maxprofit = 0;
100+
for (int price: prices) {
101+
maxprofit = Math.max(maxprofit, price - minprice);
102+
minprice = Math.min(price, minprice);
103+
}
104+
return maxprofit;
105+
}
106+
}
107+
```
108+
109+
Python Code:
110+
111+
```python
112+
class Solution:
113+
def maxProfit(self, prices: 'List[int]') -> int:
114+
if not prices: return 0
114115

116+
min_price = float('inf')
117+
max_profit = 0
115118

119+
for price in prices:
120+
if price < min_price:
121+
min_price = price
122+
elif max_profit < price - min_price:
123+
max_profit = price - min_price
124+
return max_profit
125+
```
116126

117127
## 相关题目
118128

0 commit comments

Comments
 (0)