Contents

์ฃผ์‹๊ฐ€๊ฒฉ (with.Java)

   Sep 25, 2024     2 min read

์ฃผ์‹๊ฐ€๊ฒฉ (with.Java) ์— ๋Œ€ํ•˜์—ฌ ์•Œ์•„๋ณธ ๊ธ€์ž…๋‹ˆ๋‹ค.

์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉฐ, ํ’€์—ˆ๋˜ ๋ฌธ์ œ์— ๋Œ€ํ•œ ํšŒ๊ณ ์™€ ๋‹ค๋ฅธ ํ’€์ด ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด๋ฉฐ, ์•Œ์•„๊ฐ€๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค.

๋ฌธ์ œ์— ๋Œ€ํ•ด ๋จผ์ € ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

๋ฌธ์ œ

์ดˆ ๋‹จ์œ„๋กœ ๊ธฐ๋ก๋œ ์ฃผ์‹๊ฐ€๊ฒฉ์ด ๋‹ด๊ธด ๋ฐฐ์—ด prices๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ๊ธฐ๊ฐ„์€ ๋ช‡ ์ดˆ์ธ์ง€๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์„ธ์š”.

์ œํ•œ์‚ฌํ•ญ

  • prices์˜ ๊ฐ ๊ฐ€๊ฒฉ์€ 1 ์ด์ƒ 10,000 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.
  • prices์˜ ๊ธธ์ด๋Š” 2 ์ด์ƒ 100,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ

pricesreturn
[1, 2, 3, 2, 3][4, 3, 1, 1, 0]

๋ฌธ์ œ ํ’€์ด

class Solution {
    public int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        for(int i = 0; i < prices.length - 1; i++){
            int init_0 = prices[i];
            int sec = 0;

            for(int j = i + 1; j < prices.length; j++){
                int init_1 = prices[j];
                sec++;

                if(init_0 > init_1){
                    break;
                }
            }

            answer[i] = sec;
        }
        return answer;
    }
}

ํ’€์ด ์„ค๋ช…

์ด ์ฝ”๋“œ๋Š” ์ฃผ์‹ ๊ฐ€๊ฒฉ์˜ ๋ฐฐ์—ด์„ ์ž…๋ ฅ๋ฐ›์•„ ๊ฐ ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋ช‡ ์ดˆ ๋™์•ˆ ๋–จ์–ด์ง€์ง€ ์•Š์•˜๋Š”์ง€๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ฉ๋‹ˆ๋‹ค.

๋จผ์ € ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ์‹œ๊ฐ„์„ ์ €์žฅํ•  ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

์ด ๋ฐฐ์—ด์˜ ๊ธธ์ด๋Š” ์ž…๋ ฅ ๋ฐฐ์—ด๊ณผ ๋™์ผํ•ฉ๋‹ˆ๋‹ค.

์ฒซ ๋ฒˆ์งธ ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด ๊ฐ ์ฃผ์‹ ๊ฐ€๊ฒฉ์„ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.

๋งˆ์ง€๋ง‰ ์ฃผ์‹ ๊ฐ€๊ฒฉ์€ ๋น„๊ตํ•  ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ ์ฃผ์‹ ๋ฐฐ์—ด์˜ ๊ธธ์ด์—์„œ ํ•˜๋‚˜๋ฅผ ๋บ€ ๋งŒํผ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

ํ˜„์žฌ ์ฃผ์‹ ๊ฐ€๊ฒฉ์„ ๋ณ€์ˆ˜์— ์ €์žฅํ•˜๊ณ  ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ์‹œ๊ฐ„์„ ์ €์žฅํ•  ๋ณ€์ˆ˜๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค.

๋‘ ๋ฒˆ์งธ ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด ํ˜„์žฌ ์ฃผ์‹ ๊ฐ€๊ฒฉ ์ดํ›„์˜ ์ฃผ์‹ ๊ฐ€๊ฒฉ๋“ค์„ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.

๋น„๊ตํ•  ์ฃผ์‹ ๊ฐ€๊ฒฉ์„ ๋ณ€์ˆ˜์— ์ €์žฅํ•˜๊ณ  ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ ์‹œ๊ฐ„์„ 1์ดˆ ์ฆ๊ฐ€์‹œํ‚ต๋‹ˆ๋‹ค.

ํ˜„์žฌ ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋น„๊ตํ•  ์ฃผ์‹ ๊ฐ€๊ฒฉ๋ณด๋‹ค ํฌ๋‹ค๋ฉด ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง„ ๊ฒƒ์ด๋ฏ€๋กœ ๋ฐ˜๋ณต๋ฌธ์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.

ํ˜„์žฌ ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ์‹œ๊ฐ„์„ ๋ฐฐ์—ด์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

์ด ๊ณผ์ •์„ ํ†ตํ•ด ๋ชจ๋“  ์ฃผ์‹ ๊ฐ€๊ฒฉ์— ๋Œ€ํ•ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ์‹œ๊ฐ„์„ ๊ณ„์‚ฐํ•œ ํ›„, ๊ฒฐ๊ณผ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด ์ฃผ์‹ ๊ฐ€๊ฒฉ ๋ฐฐ์—ด์ด 1, 2, 3, 2, 3์ธ ๊ฒฝ์šฐ ์ฒซ ๋ฒˆ์งธ ๊ฐ€๊ฒฉ 1์€ ๋–จ์–ด์ง€์ง€ ์•Š์€ ์‹œ๊ฐ„์ด 4์ดˆ, ๋‘ ๋ฒˆ์งธ ๊ฐ€๊ฒฉ 2๋Š” 3์ดˆ, ์„ธ ๋ฒˆ์งธ ๊ฐ€๊ฒฉ 3์€ 1์ดˆ, ๋„ค ๋ฒˆ์งธ ๊ฐ€๊ฒฉ 2๋Š” 1์ดˆ, ๋งˆ์ง€๋ง‰ ๊ฐ€๊ฒฉ 3์€ ๋น„๊ตํ•  ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ 0์ดˆ์ž…๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๊ฒฐ๊ณผ ๋ฐฐ์—ด์€ 4, 3, 1, 1, 0์ด ๋ฉ๋‹ˆ๋‹ค.

์ด ์ฝ”๋“œ๋Š” ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ์‹œ๊ฐ„์„ ํšจ์œจ์ ์œผ๋กœ ๊ณ„์‚ฐํ•˜์—ฌ ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ฉ๋‹ˆ๋‹ค.