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

Commit 8b238f6

Browse files
update 121.best-time-to-buy-and-sell-stock.java
1 parent a1461a3 commit 8b238f6

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

‎121.best-time-to-buy-and-sell-stock.java‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,18 +77,15 @@ public int maxProfit(int[] prices) {
7777
// ^
7878

7979
int profit = 0;
80-
int buyIdx = 0;
80+
int buy = Integer.MAX_VALUE;
8181

8282
for (int i = 0; i < prices.length; i++) {
8383
int curr = prices[i];
84-
int buy = prices[buyIdx];
85-
// Look for a higher price point for selling
86-
if (curr > buy && curr - buy > profit) {
87-
profit = curr - buy;
88-
}
8984
// Look for a lower price point for buying
9085
if (curr < buy) {
91-
buyIdx = i;
86+
buy = curr;
87+
} else {
88+
profit = Math.max(profit, curr - buy);
9289
}
9390
}
9491

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /