File tree Expand file tree Collapse file tree
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int maxProfit (int [] prices ) {
3+ /**
4+ 1. ํ๋ฃจ์ ํ์์ ๊ฐ์ฅ ์ต๋ ์ด์ต์ ๊ตฌํ๋๋กํ๋ max price return
5+ 2. ์กฐ๊ฑด
6+ - ๋ฏธ๋ ๋ค๋ฅธ๋ ์ง์ ํ๋งค (์ด์ ๋ ์ง์ ํ๋งค x)
7+ - choosing a single day
8+ - ๋ฐฐ์ด ๊ธธ์ด min = 1, max = 10^5
9+ - ์์๊ฐ : min = 0, max = 10^4
10+ 3. ํ์ด
11+ - 1)brtueforce: time complexity O(n^2), space: O(1)
12+ - 2)ํ์ฌ ๊ฐ - ์ด์ ๊ฐ ์ค ๊ฐ์ฅ ์ต์๊ฐ -> maxProfit , ์ฆ min๊ฐ์ ๊ณ์ ๊ธฐ์ตํ๋ค๊ฐ ํ์ฌ ๊ฐ๊ณผ์ ์ฐจ์ด ์ค ๊ฐ์ฅ ํฐ ๊ฐ์ ๊ตฌํ๋ฉด๋๋ค.
13+ - time: O(n)
14+ - space: O(1)
15+ */
16+
17+ int maxProfit = 0 ;
18+ int minStock = Integer .MAX_VALUE ;
19+ int n = prices .length ;
20+
21+ for (int i = 0 ; i <n ; i ++) {
22+ if (prices [i ] < minStock ) {
23+ minStock = prices [i ];
24+ }
25+ if (i > 0 && prices [i ] - minStock > maxProfit ) {
26+ maxProfit = Math .max (maxProfit , prices [i ] - minStock );
27+ }
28+ }
29+ return maxProfit ;
30+
31+
32+ // for(int i = 0; i < n; i++) {
33+ // int curStock = prices[i];
34+ // for(int j= i + 1; j < n; j++) {
35+ // if(curStock < prices[j]) {
36+ // int curProfit = prices[j] - curStock;
37+ // maxProfit = Math.max(maxProfit, curProfit);
38+ // }
39+ // }
40+ // }
41+ // return maxProfit;
42+ }
43+ }
You canโt perform that action at this time.
0 commit comments