|
| 1 | +class Solution { |
| 2 | + public int maxProfit(int[] prices) { |
| 3 | + // 1. 0๋ฒ์ ์ ์ธํ๊ณ max ๋ฅผ ์ฐพ๊ณ |
| 4 | + // 2. 0 ~ max ๋ฒ์์์ min์ ์ฐพ๋๋ค => 2n |
| 5 | + // 3. max - min > 0 ์ด๋ฉด ๊ฐ ๋ฆฌํด, max - min <=0 ์ด๋ฉด 0 ๋ฆฌํด |
| 6 | + /* |
| 7 | + if (prices.length == 1) { |
| 8 | + return 0; |
| 9 | + } |
| 10 | +
|
| 11 | + int max = 1; |
| 12 | + for (int i = 1; i < prices.length; i++) { |
| 13 | + if (prices[max] <= prices[i]) { |
| 14 | + max = i; |
| 15 | + } |
| 16 | + } |
| 17 | +
|
| 18 | + int min = max - 1; |
| 19 | + for (int i = max - 1; i >= 0; i--) { |
| 20 | + if (prices[i] < prices[min]) { |
| 21 | + min = i; |
| 22 | + } |
| 23 | + } |
| 24 | + int result = prices[max] - prices[min]; |
| 25 | + return result > 0 ? result : 0; |
| 26 | + */ |
| 27 | + // ์ ํ์ด ์คํจ ์ผ์ด์ค : [3,3,5,0,0,3,1,4] |
| 28 | + // -> i๊ฐ max ์ผ ๋ i ์ด์ ๊น์ง ๋ฐ๋ณต๋ฌธ์ผ๋ก ์ต๋๊ฐ ๊ตฌํ๊ธฐ => n^2 |
| 29 | + // -> Time Limit Exceeded ๋ฐ์ |
| 30 | + // -> i ์ด์ ๊น์ง ๋ฒ์์์ ์ต์๊ฐ์ ๊ตฌํด์ ๊ฐ์ ๊ตฌํ ๊น? |
| 31 | + /* |
| 32 | + int result = 0; |
| 33 | + for (int i = 1; i < prices.length; i++) { |
| 34 | + for (int j = 0; j < i; j++) { |
| 35 | + int cur = prices[i] - prices[j]; |
| 36 | + if (result < cur) { |
| 37 | + result = cur; |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + return result; |
| 42 | + */ |
| 43 | + // i ์ด์ ๊น์ง ๋ฒ์์์ ์ต์๊ฐ์ ๊ตฌํด์ ๋ฐฐ์ด๋ก ๋ง๋ค๊ธฐ |
| 44 | + int curMin = prices[0]; |
| 45 | + int result = 0; |
| 46 | + for (int i = 0; i < prices.length; i++) { |
| 47 | + if (curMin > prices[i]) { |
| 48 | + curMin = prices[i]; |
| 49 | + } |
| 50 | + // System.out.println(curMin); |
| 51 | + if (result < prices[i] - curMin) { |
| 52 | + result = prices[i] - curMin; |
| 53 | + } |
| 54 | + // System.out.println(">>" + result); |
| 55 | + } |
| 56 | + return result; |
| 57 | + } |
| 58 | +} |
0 commit comments