File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Time complexity: O(n)
3+ Space complexity: O(1)
4+
5+ i <= j ์ธ ๋ ์ธ๋ฑ์ค i, j์ ๋ํด์, prices[j] - prices[i]๋ฅผ ์ต๋ํํด์ผ ํ๋ค.
6+
7+ 1. i = 0๋ถํฐ ์์ํ์ฌ, ์ค๋ฅธ์ชฝ์ผ๋ก ์ํํ๋ค.
8+ 2. ํ์ฌ ๊ฐ์ด max๋ณด๋ค ํฌ๋ค๋ฉด, max๋ฅผ ๊ฐฑ์ ํ๊ณ , min๊ณผ์ ์ฐจ์ด๋ฅผ ๊ณ์ฐํ๋ค.
9+ 3. ํ์ฌ ๊ฐ์ด min๋ณด๋ค ์๋ค๋ฉด, min์ ๊ฐฑ์ ํ๊ณ , max ์ญ์ ๊ฐ์ ๊ฐ์ผ๋ก ๊ฐฑ์ ํ๋ค. (๊ณผ๊ฑฐ๋ก ๋์๊ฐ์ ํ ์๋ ์์ผ๋ฏ๋ก)
10+ */
11+ class Solution {
12+ public int maxProfit (int [] prices ) {
13+ int min = 999999 ;
14+ int max = 0 ;
15+ int ans = 0 ;
16+ for (int i = 0 ; i < prices .length ; i ++) {
17+ if (prices [i ] > max ) {
18+ max = prices [i ];
19+ if (max - min > ans ) {
20+ ans = max - min ;
21+ }
22+ }
23+ if (prices [i ] < min ) {
24+ min = max = prices [i ];
25+ }
26+ }
27+
28+ return ans ;
29+ }
30+ }
You canโt perform that action at this time.
0 commit comments