Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit13cd026

Browse files
committed
121 (3) add README
1 parent273ed68 commit13cd026

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
####[121] Best to Buy and Sell Stock
2+
3+
0. Brutal Force: O(N^2) solution
4+
5+
```plain
6+
For each stock price, // -> O(M)
7+
we want to find the lowest price beforehands. // O(N)
8+
```
9+
10+
1. O(N) solution
11+
12+
Save the lowest price before

‎src/_121_BestTimeToBuyAndSellStock/Solution.java

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,15 @@
2222
publicclassSolution {
2323

2424
publicintmaxProfit(int[]prices) {
25-
intresult =0;
25+
intresult =0;
26+
// lowest price so far
2627
intminPrice =Integer.MAX_VALUE;
2728
for (intprice :prices) {
28-
// sell stock at current price
29-
// find the minimum price before this way
30-
minPrice =Math.min(minPrice,price);
3129

32-
// profit = minPrice < price ? (price - minPrice) : 0;
33-
// profit = Math.max(price - minPrice, 0);
30+
minPrice =Math.min(minPrice,price);
3431

3532
result =Math.max(result,price -minPrice);
33+
3634
}
3735
returnresult;
3836
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp