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

Commitf0e41cb

Browse files
EASY/src/easy/BestTimeToBuyAndSellStock.java
1 parent71a28e6 commitf0e41cb

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

‎EASY/src/easy/BestTimeToBuyAndSellStock.java

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,19 +43,16 @@ public static void main(String...strings){
4343
System.out.println(test.maxProfit(prices));
4444
}
4545

46-
publicintmaxProfit_attemp1(int[]prices) {
47-
if(prices ==null ||prices.length <2)return0;
48-
intminBuy =prices[0],maxSell =prices[1],maxProfit =0;
46+
47+
/**Pretty straightforward, sell before you buy, keep a global maxProfit variable, update it along the way if necessary.*/
48+
publicintmaxProfit_20160924(int[]prices) {
49+
if(prices ==null ||prices.length ==0 ||prices.length <2)return0;
50+
intminBuy =prices[0];
51+
intmaxSell =prices[1];
52+
intmaxProfit = (maxSell -minBuy) >0 ? (maxSell -minBuy) :0;
4953
for(inti =1;i <prices.length;i++){
50-
if(maxSell >minBuy){
51-
maxProfit =Math.max(maxProfit,maxSell-minBuy);
52-
}
53-
if(prices[i] <minBuy){
54-
minBuy =prices[i];
55-
}
56-
if(prices[i] >maxSell){
57-
maxSell =prices[i];
58-
}
54+
minBuy =Math.min(minBuy,prices[i]);
55+
maxProfit =Math.max(maxProfit,prices[i] -minBuy);
5956
}
6057
returnmaxProfit;
6158
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp