|
| 1 | +// ํ์ด ๋ฐฉ๋ฒ |
| 2 | +// 1. ์ธ๋ฑ์ค x๊น์ง์ ์ต์๊ฐ์ ์ ์ฅํ๋ ๋ฐฐ์ด 1๊ฐ์, ์ธ๋ฑ์ค x๋ถํฐ์ ์ต๋๊ฐ์ ์ ์ฅํ๋ ๋ฐฐ์ด 1๊ฐ๋ฅผ ๋ง๋ ๋ค. |
| 3 | +// 2. 1๋ฒ์์ ๋ง๋ ๋ ๋ฐฐ์ด์ ๊ฐ์ ์ฑ์ด๋ค. |
| 4 | +// 3. ๋ ๋ฐฐ์ด์ ๊ฐ๊ฐ ์ธ๋ฑ์ค ๋ณ๋ก ์ฐจ๋ฅผ ๊ตฌํ๊ณ , ๊ทธ ์ค ์ต๋๊ฐ์ ๊ตฌํ๋ค. |
| 5 | + |
| 6 | +// ์๊ฐ ๋ณต์ก๋ |
| 7 | +// O(n) : ๋ฐฐ์ด์ 2๋ฒ ์ํํ๋ฏ๋ก O(n)์ด๋ค. |
| 8 | +// ๊ณต๊ฐ ๋ณต์ก๋ |
| 9 | +// O(n) : ์ต์๊ฐ๊ณผ ์ต๋๊ฐ์ ์ ์ฅํ๋ ๋ฐฐ์ด์ ๋ง๋ค์์ผ๋ฏ๋ก O(n)์ด๋ค. |
| 10 | + |
| 11 | +class Solution { |
| 12 | + public int maxProfit(int[] prices) { |
| 13 | + int len = prices.length; |
| 14 | + int[] minArr = new int[len]; |
| 15 | + int[] maxArr = new int[len]; |
| 16 | + |
| 17 | + for(int i=0;i<len;i++){ |
| 18 | + if(i==0){ |
| 19 | + minArr[i] = prices[i]; |
| 20 | + maxArr[len-i-1] = prices[len-i-1]; |
| 21 | + }else{ |
| 22 | + minArr[i] = Math.min(minArr[i-1], prices[i]); |
| 23 | + maxArr[len-i-1] = Math.max(maxArr[len-i], prices[len-i-1]); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + int result = 0; |
| 28 | + for(int i=0;i<len;i++){ |
| 29 | + result = Math.max(result, maxArr[i]-minArr[i]); |
| 30 | + } |
| 31 | + return result; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +// 2nd solution |
| 37 | +// ์๊ฐ ๋ณต์ก๋: O(n) |
| 38 | +// ๊ณต๊ฐ ๋ณต์ก๋: O(1) |
| 39 | + |
| 40 | +class Solution{ |
| 41 | + public int maxProfit(int[] prices){ |
| 42 | + int len = prices.length; |
| 43 | + int buy = prices[0]; |
| 44 | + int result = 0; |
| 45 | + |
| 46 | + for(int i=1;i<len;i++){ |
| 47 | + if(prices[i]<buy){ // ๋ ์ ๋ ดํ ์ฃผ์์ด ์์ผ๋ฏ๋ก |
| 48 | + buy = prices[i]; // ์ด ์ฃผ์์ ์ฐ๋ค. |
| 49 | + }else{ |
| 50 | + result = Math.max(result, prices[i]-buy); // ํ์ฌ ์ฃผ์์ ํ์์ ๋ ์ด๋์ด ๋ ํฌ๋ค๋ฉด ํ๋ค. |
| 51 | + } |
| 52 | + } |
| 53 | + return result; |
| 54 | + } |
| 55 | +} |
0 commit comments