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 02145d9

Browse files
Create 121. Best Time to Buy and Sell Stock
1 parent 06d9498 commit 02145d9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎121. Best Time to Buy and Sell Stock‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
int[] left = new int[prices.length];
4+
int[] right = new int[prices.length];
5+
left[0] = prices[0];
6+
right[prices.length-1] = prices[prices.length-1];
7+
for(int i = 1; i < prices.length; i++) {
8+
lfeft[i]= Math.min(left[i-1], prices[i]);
9+
}
10+
for(int i = prices.length-2; i >= 0; i--) {
11+
right[i] = Math.max(right[i+1], prices[i]);
12+
}
13+
int max = 0;
14+
for(int i = 0; i < prices.length; i++) {
15+
max = Math.max(max, right[i]-left[i]);
16+
}
17+
return max;
18+
}
19+
}
20+
21+
class Solution {
22+
public int maxProfit(int[] prices) {
23+
24+
int minPrice = Integer.MAX_VALUE;
25+
int maxProfit = 0;
26+
for(int i = 0; i < prices.length; i++) {
27+
if(prices[i] < minPrice)
28+
minPrice = prices[i];
29+
maxProfit = Math.max(prices[i] - minPrice, maxProfit);
30+
}
31+
32+
return maxProfit;
33+
}
34+
}

0 commit comments

Comments
(0)

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