๐Ÿ’ญ Problem Solving

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][C++] ํฐ ์ˆ˜ ๋งŒ๋“ค๊ธฐ

0=2. 2024. 6. 2. 23:13

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/42883

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

๐Ÿ’ก ๋ฌธ์ œ ์ ‘๊ทผ

  • k๊ฐœ์˜ ์ˆ˜๋ฅผ ์ œ๊ฑฐ = ( number.length() - k )๊ฐœ์˜ ์ˆ˜๋ฅผ ๋ฝ‘๋Š” ๊ฒƒ
  • ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ๋ฝ‘๋Š”๋‹ค.
  • ์•ž ์ž๋ฆฌ๊ฐ€ ํด ์ˆ˜๋ก ํฌ๋‹ค.
1. 0๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ k๋ฒˆ์งธ๊นŒ์ง€์˜ ๋ฒ”์œ„ ๋‚ด์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค.
2. ๋ฝ‘์€ ์ˆ˜ (๊ฐ€์žฅ ํฐ ์ˆ˜)๋ฅผ answer์— ์‚ฝ์ž…ํ•˜๊ณ  ๊ทธ ์ˆ˜์˜ ์ธ๋ฑ์Šค๋ฅผ ์ €์žฅํ•œ๋‹ค.
3. ๋ฝ‘์€ ์ˆ˜์˜ ์ธ๋ฑ์Šค ๋‹ค์Œ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ๋‹ค์‹œ ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค. ์ด๋•Œ, ํƒ์ƒ‰ ๋ฒ”์œ„๋ฅผ 1 ๋Š˜๋ ค์ค€๋‹ค. (k + i ํ™œ์šฉ)

 

(ex) number = "4177252841" / k = 4 / answer์˜ ์ž๋ฆฟ์ˆ˜ = 10 - 4 = 6์ž๋ฆฌ

  1. 0 ~ 4๋ฒˆ์งธ "41772" ์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜ = 7 / idx = 2/ answer = "7"
  2. 3 ~ 5๋ฒˆ์งธ "725" ์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜ = 7  / idx = 3 / answer = "77"
  3. 4 ~ 6๋ฒˆ์งธ "252" ์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜ = 5  / idx = 5 / answer = "775"
  4. 6 ~ 7๋ฒˆ์งธ "28" ์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜ = 8  / idx = 7 / answer = "7758"
  5. 8 ~ 8๋ฒˆ์งธ "4" ์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜ = 4 / idx = 8 /  answer = "77584"
  6. 9 ~ 9๋ฒˆ์งธ "1" ์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜ = 1 / idx = 9 /  answer = "775841"

์ฝ”๋“œ

#include <iostream>
#include <vector>

using namespace std;

string solution(string number, int k) {
    string answer = "";
    int idx = -1;

    // number.length() - k ์ˆ˜ ๋ฝ‘๊ธฐ
    for (int i = 0; i < number.length() - k; i++) {
        char max_num = '0';
        for (int j = idx + 1; j <= k + i; j++) {    // ๊ฐ€์žฅ ํฐ ์ˆ˜ ์ฐพ๊ธฐ
            if (max_num < number[j]) {
                max_num = number[j];
                idx = j;
            }
        }
        answer += max_num;
    }

    return answer;
}