Skip to content

Commit a69f3a8

Browse files
committed
feat: add the solution of Best Time to Buy and Sell Stock(121) with kotlin.
1 parent a6e9ffc commit a69f3a8

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
| [112][112-question] | [Path Sum][112-tips] | [][112-java] | | [][112-kotlin] |
5858
| [118][118-question] | [Pascal's Triangle][118-tips] | [][118-java] | | [][118-kotlin] |
5959
| [119][119-question] | [Pascal's Triangle II][119-tips] | [][119-java] | | [][119-kotlin] |
60-
| [121][121-question] | [Best Time to Buy and Sell Stock][121-tips] | [][121-java] | | |
60+
| [121][121-question] | [Best Time to Buy and Sell Stock][121-tips] | [][121-java] | | [][121-kotlin] |
6161
| [122][122-question] | [Best Time to Buy and Sell Stock II][122-tips] | [][122-java] | | |
6262
| [226][226-question] | [Invert Binary Tree][226-tips] | [][226-java] | [][226-js] | |
6363
| [543][543-question] | [Diameter of Binary Tree][543-tips] | [][543-java] | | |
@@ -516,4 +516,5 @@
516516
[112-kotlin]: ./src/_112/kotlin/Solution.kt
517517
[118-kotlin]: ./src/_118/kotlin/Solution.kt
518518
[119-kotlin]: ./src/_119/kotlin/Solution.kt
519+
[121-kotlin]: ./src/_121/kotlin/Solution.kt
519520
[771-kotlin]: ./src/_771/kotlin/Solution.kt

src/_121/kotlin/Solution.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package _121.kotlin
2+
3+
/**
4+
* @author relish
5+
* @since 2018/05/07
6+
*/
7+
class Solution {
8+
fun maxProfit(prices: IntArray): Int {
9+
if (prices.isEmpty()) return 0
10+
var ret = 0
11+
var min = prices[0]
12+
for (i in 1 until prices.size) {
13+
min = Math.min(min, prices[i])
14+
ret = Math.max(prices[i] - min, ret)
15+
}
16+
return ret
17+
}
18+
}
19+
20+
fun main(args: Array<String>) {
21+
println(Solution().maxProfit(intArrayOf(7, 1, 5, 3, 6, 4)))
22+
println(Solution().maxProfit(intArrayOf(7, 6, 4, 3, 1)))
23+
}

tips/121/README.md

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

3232
题意是给出一个数组代表每天的股票金额,让你在最多买卖一次的情况下算出最大的收益额,最简单的就是模拟即可,每次记录当前值减去最小值的差值,与上一次的进行比较然后更新最大值即可。
3333

34+
Java:
3435
```java
3536
class Solution {
3637
public int maxProfit(int[] prices) {
@@ -45,6 +46,21 @@ class Solution {
4546
}
4647
```
4748

49+
kotlin(204ms/100.00%):
50+
```kotlin
51+
class Solution {
52+
fun maxProfit(prices: IntArray): Int {
53+
if (prices.isEmpty()) return 0
54+
var ret = 0
55+
var min = prices[0]
56+
for (i in 1 until prices.size) {
57+
min = Math.min(min, prices[i])
58+
ret = Math.max(prices[i] - min, ret)
59+
}
60+
return ret
61+
}
62+
}
63+
```
4864

4965
## 结语
5066

0 commit comments

Comments
 (0)