<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>dev-eunji</title>
        <link>https://velog.io/</link>
        <description>안녕하세요 :) </description>
        <lastBuildDate>Mon, 15 Aug 2022 09:06:29 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <copyright>Copyright (C) 2019. dev-eunji. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/dev-eunji" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[Lv2. 행렬의 곱셈]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%ED%96%89%EB%A0%AC%EC%9D%98-%EA%B3%B1%EC%85%88</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%ED%96%89%EB%A0%AC%EC%9D%98-%EA%B3%B1%EC%85%88</guid>
            <pubDate>Mon, 15 Aug 2022 09:06:29 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12949">코딩테스트 연습 &gt; 행렬의 곱셈</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>행렬의 곱셈은 <code>(i * j) * (j * k) = (i * k)</code> 이다.</p>
</li>
<li><p><code>answer</code> 를 <code>(i * k)</code> 크기의 0 을 갖는 리스트로 초기화한다.</p>
</li>
<li><p>i, j, k 를 각각 3중 for문을 돌면서 (arr1, arr2 의 최대 크기는 100이다.)
<code>answer[i][k] += arr1[i][j] * arr2[j][k]</code> 로 업데이트하여 <code>answer</code> 를 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(arr1, arr2):
    len_i = len(arr1)
    len_j = len(arr1[0])
    len_k = len(arr2[0])
    answer = [[0] * len_k for _ in range(len_i)]

    for i in range(len_i):
        for j in range(len_j):
            for k in range(len_k):
                answer[i][k] += arr1[i][j] * arr2[j][k]

    return answer</code></pre>
<h4 id="kotlin">kotlin</h4>
<pre><code class="language-kotlin">fun solution(arr1: Array&lt;IntArray&gt;, arr2: Array&lt;IntArray&gt;): Array&lt;IntArray&gt; {
    val lenI = arr1.size
    val lenJ = arr1[0].size
    val lenK = arr2[0].size
    var answer = Array(lenI) { IntArray(lenK) }
    for(i in 0 until lenI) {
        for(j in 0 until lenJ) {
           for(k in 0 until lenK) {
                answer[i][k] += arr1[i][j] * arr2[j][k]
            }
        }
    }
    return answer
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 3 x n 타일링]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-3-x-n-%ED%83%80%EC%9D%BC%EB%A7%81-sznoh8up</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-3-x-n-%ED%83%80%EC%9D%BC%EB%A7%81-sznoh8up</guid>
            <pubDate>Mon, 15 Aug 2022 08:53:35 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12902">코딩테스트 연습 &gt; 3 x n 타일링</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>홀수인 경우에는 직사각형을 채울 수 없다.</p>
</li>
<li><p><code>memo</code> 리스트를 0으로 초기화하고, 
n이 2인 경우에는 3, n이 4인 경우에는 11로 초기화한다.</p>
</li>
<li><p>2중 for문을 돌면서 <code>memo[i]</code> 를 업데이트 한다.</p>
</li>
</ol>
<ul>
<li><p>6부터 n까지 for문을 돌면서 <code>memo[i] = memo[i-2] * 3 + 2</code></p>
<ul>
<li><code>i-2</code> 길이를 채우고, 남은 길이2를 채울 수 있는 방법 3가지</li>
<li>특별한 케이스: <code>+2</code></li>
</ul>
</li>
<li><p><code>i-4</code>부터 2까지 <code>j</code>가 2씩 작아지면서<code>memo[i] += 2 * memo[j]</code> </p>
<ul>
<li>각 길이까지 채우고(memo[j]), 남은 길이를 특별한 케이스로 채울 수 있는 방법이</li>
</ul>
</li>
<li><p>예를 들어 n = 8이라면, </p>
<ul>
<li>6칸 채우고, 남은 2칸을 채우는 방법 3가지 <code>memo[8] = memo[6] * 3</code></li>
<li>8 특별한 케이스: <code>+2</code></li>
<li>4 칸 채우고, 남은 4칸의 특별한 케이스 <code>* memo[4]</code> :<code>memo[8] += 2 * memo[4]</code></li>
<li>2칸 채우고, 남은 6칸의 특별한 케이스 <code>* memo[2]</code> :<code>memo[8] += 2 * memo[2]</code></li>
</ul>
</li>
</ul>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(n):
    if n % 2 != 0:
        return 0
    memo = [0] * (n+1)
    memo[2] = 3
    memo[4] = 11
    for i in range(6, n+1, 2):
        memo[i] = memo[i-2] * 3 + 2
        for j in range(i-4, 0, -2):
            memo[i] += 2 * memo[j]
        memo[i] = memo[i] % 1000000007
    return memo[n]</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ul>
<li><p>규칙을 찾기 어려웠던 문제다.</p>
</li>
<li><p><a href="https://velog.io/@dev-eunji/Lv2.-2-x-n-%ED%83%80%EC%9D%BC%EB%A7%81">참고 문제</a></p>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 피로도]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%ED%94%BC%EB%A1%9C%EB%8F%84</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%ED%94%BC%EB%A1%9C%EB%8F%84</guid>
            <pubDate>Mon, 15 Aug 2022 07:34:02 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/87946">코딩테스트 연습 &gt; 피로도</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p><code>dungeons</code> 의 크기가 최대 8이므로 완전탐색, 순열을 사용하여 문제를 풀었다.</p>
</li>
<li><p><code>dungeons</code> 를 순열로 만들어서 모든 경우에 대해 <code>count</code> 를 계산하고 최대 <code>count</code> 를 반환한다.</p>
<ul>
<li><code>python</code>: <code>permutations</code></li>
<li><code>kotlin</code>: <code>dfs</code></li>
</ul>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">from itertools import permutations

def solution(k, dungeons):
    answer = 0
    for dungeon in permutations(dungeons, len(dungeons)):
        current = k
        count = 0
        for d in dungeon:
            if current &gt;= d[0]:
                current -= d[1]
                count += 1
        answer = max(answer, count)
    return answer</code></pre>
<h4 id="kotlin">kotlin</h4>
<pre><code class="language-kotlin">class Solution {
    private val visited = BooleanArray(8)
    private var count = 0
    private var answer = 0

    fun solution(k: Int, dungeons: Array&lt;IntArray&gt;): Int {
        for (i in dungeons.indices) {
            dfs(k, i, dungeons)
        }
        return answer
    }

    private fun dfs(k: Int, current: Int, dungeons: Array&lt;IntArray&gt;) {
        for (i in dungeons.indices) {
            if (visited[i].not() &amp;&amp; k &gt;= dungeons[i][0]) {
                visited[i] = true
                count += 1
                answer = Math.max(answer, count)
                dfs(k - dungeons[i][1], i, dungeons)
                visited[i] = false
                count -= 1
            }
        }
    }
}</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li>순열로 완전탐색 풀기</li>
</ol>
<ul>
<li>python 순열<pre><code class="language-python">from itertools import permutations
</code></pre>
</li>
</ul>
<p>permutations(list, len(list))</p>
<pre><code>
- kotlin 순열
```kotlin
fun a() {
    for (i in list.indices) {
        dfs(i, list)
    }
}

fun dfs(current: Int, list: List) {
    for (i in list.indices) {
        visited[i] = true
        dfs(i, list)
        visited[i] = false
    }
}</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 방문 길이]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EB%B0%A9%EB%AC%B8-%EA%B8%B8%EC%9D%B4</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EB%B0%A9%EB%AC%B8-%EA%B8%B8%EC%9D%B4</guid>
            <pubDate>Sun, 14 Aug 2022 10:27:32 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/49994">코딩테스트 연습 &gt; 방문 길이</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>&quot;지나가 본 길을 어떻게 저장할지&quot; 가 중요한 문제다.</p>
</li>
<li><p>출발점인 <code>(0,0)</code> 을 <code>visited[5][5]</code> 위치로 설정했다. 
점 사이를 거리로 보고, 각 위치의 점은 4개의 False 로 초기화한 아이템을 갖는 list 값을 갖는다.
list는 방문 여부에 대한 flag 이다. (오른쪽에서 방문, 아래에서 방문, 왼쪽에서 방문, 위에서 방문)
예를 들어, 출발점인 (5,5)는 <code>visited[5][5]</code> 이고, <code>visited[5][5] = [False, False, False, False]</code> 로 초기화 되어있다.</p>
</li>
</ol>
<pre><code>(6,4)  (6,5)  (6,6) 
-----------------
|          |        |
-----------------
(5,4)  (5,5)  (5,6)</code></pre><ol start="3">
<li><code>dirs</code> 를 for문 돌면서, index 가능여부를 체크를 하고 이동이 가능하다면,
 3-1.<code>d</code>에 맞게 이동을 시킨다.
 3-2. 방문한 적이 없다면, 방문 체크를 한 후에 answer +1 을 해준다.<pre><code> (이동 후의 점에 해당하는 거리와 이동 전 점에 해당하는 거리의 방문 여부를 모두 True 로 변경한다.)</code></pre><pre><code>ex) (3,5) 위치에서 d 가 &quot;U&quot; 라면
y 는 4가 되고 (3,5) 에서 (4,5) 로 이동하는 것이기 때문에
visited[4][5][1] = True # (4,5) 의 아래에서 방문 여부 True 
visited[3][5][3] = True # (3,5) 의 위에서 방문 여부 True</code></pre></li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(dirs):
    answer = 0

    # R, D, L, U
    visited = [[[False, False, False, False]  for _ in range(11)] for _ in range(11)]
    y, x = 5, 5

    for d in dirs:
        if d == &quot;U&quot;:
            if 0 &lt;= y &lt; 10:
                y += 1
                if not visited[y][x][1] and not visited[y-1][x][3]:
                    visited[y][x][1] = True
                    visited[y-1][x][3] = True
                    answer += 1
        elif d == &quot;D&quot;:
            if 0 &lt; y &lt;= 10:
                y -= 1
                if not visited[y][x][3] and not visited[y+1][x][1]:
                    visited[y][x][3] = True
                    visited[y+1][x][1] = True
                    answer += 1
        elif d == &quot;R&quot;:
            if 0 &lt;= x &lt; 10:
                x += 1
                if not visited[y][x][2] and not visited[y][x-1][0]:
                    visited[y][x][2] = True
                    visited[y][x-1][0] = True
                    answer += 1
        else:
            if 0 &lt; x &lt;= 10:
                x -= 1
                if not visited[y][x][0] and not visited[y][x+1][2]:
                    visited[y][x][0] = True
                    visited[y][x+1][2] = True
                    answer += 1
    return answer</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 타겟 넘버]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%ED%83%80%EA%B2%9F-%EB%84%98%EB%B2%84</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%ED%83%80%EA%B2%9F-%EB%84%98%EB%B2%84</guid>
            <pubDate>Sun, 14 Aug 2022 08:27:27 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/43165">코딩테스트 연습 &gt; 타겟 넘버</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li>아래와 같은 tree 를 생각하면서 문제를 풀었다.</li>
</ol>
<pre><code>                                                                                    n
                        0                                            level 1            

          1                             -1                            level 2            1

    2           0               0               -2                    level 3            1

3       1   1       -1      1       -1      -1      -3                level 4            1</code></pre><ol start="2">
<li><p><code>parent</code> 리스트에 0을 넣어 초기화하며, <code>numbers</code> for문을 돌면서 (<code>n</code>) 트리가 한 층씩 내려간다.</p>
</li>
<li><p><code>parent</code> 아이템에 <code>+n</code>, <code>-n</code> 을 한 값들로 <code>parent</code> 를 업데이트 해준다.</p>
</li>
<li><p><code>parent</code> 리스트 아이템들 중에서 <code>target</code> 의 개수를 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(numbers, target):
    parent = [0]
    for n in numbers:
        children = []
        for p in parent:
            children.append(p + n)
            children.append(p - n)
        parent = children
    return sum([1 for p in parent if p == target])</code></pre>
<h4 id="kotlin">kotlin</h4>
<pre><code>fun solution(numbers: IntArray, target: Int): Int {
    var parent = mutableListOf(0)
    numbers.forEach { number -&gt;
        val children = mutableListOf&lt;Int&gt;()
        parent.forEach { node -&gt;
            children.add(node + number)
            children.add(node - number)
        }
        parent = children
    }
    return parent.count { it == target }
}</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 게임 맵 최단거리]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EA%B2%8C%EC%9E%84-%EB%A7%B5-%EC%B5%9C%EB%8B%A8%EA%B1%B0%EB%A6%AC</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EA%B2%8C%EC%9E%84-%EB%A7%B5-%EC%B5%9C%EB%8B%A8%EA%B1%B0%EB%A6%AC</guid>
            <pubDate>Sun, 14 Aug 2022 06:40:37 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/1844">코딩테스트 연습 &gt; 게임 맵 최단거리</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>전형적인 <code>BFS</code>문제다. 방향좌표 <code>dx</code>, <code>dy</code> 를 활용하여 map 을 최단거리로 이동해야 한다.</p>
</li>
<li><p><code>visited</code> 리스트에는 현재 위치에 거리가 저장된다. 
<code>visited[0][0] = 1</code> 로, <code>queue</code> 에는 <code>(0, 0)</code> 을 넣어 초기화한다.</p>
</li>
<li><p><code>queue</code> 의 아이템을 하나씩 빼면서 비지 않을 때 까지 돌고, 
<code>queue</code> 에서 빼낸 현재 위치에서 방향좌표에 따라 한 step 씩 움직이며 
<code>visited</code>와 <code>queue</code> 를 업데이트 한다.</p>
</li>
<li><p><code>visited</code> 의 마지막 위치(<code>visited[-1][-1]</code>)를 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">import collections

def solution(maps):
    return bfs(maps)

def bfs(maps):
    dy, dx = [0, -1, 0, 1], [1, 0, -1, 0]
    n, m = len(maps), len(maps[0])
    visited = [[-1] * m for _ in range(n)] 
    visited[0][0] = 1
    queue = collections.deque([(0, 0)])

    while queue:
        y, x = queue.popleft()
        for i in range(4):
            ny, nx = y + dy[i], x + dx[i]
            if 0 &lt;= ny &lt; n and 0 &lt;= nx &lt; m:
                if visited[ny][nx] == -1 and maps[ny][nx] == 1:
                    visited[ny][nx] = visited[y][x] + 1
                    queue.append((ny, nx))

    return visited[-1][-1]    </code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li><p>행렬 map을 다룰 때 주의할 점
<code>n * m</code> 행렬에서 ** 행 == n == y ** 이다. 
위치를 표현할 때 <code>(x, y)</code> 라고 말하지만 실제 <code>x</code> 위치에는 행에 해당하는 <code>y</code> 를 놓고 문제를 풀어야 한다.</p>
</li>
<li><p>아래 둘은 다르다.</p>
</li>
</ol>
<pre><code class="language-python">visited = [[-1] * m] * n

visited = [[-1] * m for _ in range(n)] </code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. [1차] 캐시]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-1%EC%B0%A8-%EC%BA%90%EC%8B%9C</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-1%EC%B0%A8-%EC%BA%90%EC%8B%9C</guid>
            <pubDate>Sat, 13 Aug 2022 13:53:35 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/49993">코딩테스트 연습 &gt; 스킬트리</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p><code>cacheSize</code> 가 0인 경우에는 캐시를 사용하지 않으므로 <code>5 * cities</code> 의 사이즈를 반환한다.</p>
</li>
<li><p><code>cities</code> 를 돌면서, <code>city</code> 를 모두 lowerCase로 변경한다 (대소문자 구분 없음)</p>
</li>
<li><p><code>city</code> 가 cache 에 있다면 (cache hit) 으로 +1 후에 cache 의 key 값으로 city 를 value 로 idx 를 저장한다.</p>
<ul>
<li>idx 는 얼마나 최근에 참조되었는지를 나타낸다.</li>
</ul>
</li>
<li><p><code>city</code> 가 cache 에 없다면, cache 사이즈를 검사하고 cache 사이즈가 <code>casheSize</code> 보다 작다면 <code>cache[city] = idx</code> 로 저장한다. 그 외 cache 가 찼다면 <code>cache</code> 중 가장 작은 value 값을 찾고, 가장 작은 value 값을 갖는 item을 pop 한 후에 <code>cache[city] = idx</code> 를 저장한다. (새로운 city 저장)</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(cacheSize, cities):
    answer = 0
    cache = {}

    if cacheSize == 0:
        return 5 * len(cities)

    for idx, city in enumerate(cities):
        city = city.lower()
        if city in cache:   # cache hit
            answer += 1
            cache[city] = idx
        else:               # cache miss
            answer += 5
            if len(cache) &lt; cacheSize:
                cache[city] = idx
            else:
                least = min(cache.values())
                for key, value in cache.items() :
                    if value == least:
                        cache.pop(key)
                        cache[city] = idx
                        break
    return answer
</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li>OS 페이지 교체 알고리즘</li>
</ol>
<p>운영체제에서 메모리를 관리할 때, 현재 페이지 중 어떤 것과 교체할 지를 결정하는 알고리즘이다.
대표적으로 <code>FIFO</code> <code>LFU</code> <code>LRU</code> 등이 있다.</p>
<p>그 중 <code>LRU (Least Recently Used Algorithm)</code> 는 가장 오랫동안 참조되지 않은 페이지를 교체하는 알고리즘이다.
단점으로는 프로세스가 참조한 페이지의 시간을 기록해야하는 오버헤드 발생한다는 점이다.</p>
<ol start="2">
<li>dictionary 조회</li>
</ol>
<pre><code class="language-python">for key, value in dictionary.items():
    print(key, value)</code></pre>
<ol start="3">
<li><code>deque</code> 의 최대 길이를 설정하여 푸는 풀이도 있다. (다른 사람 풀이 참고)</li>
</ol>
<ul>
<li>함수 내에서 <code>import</code> 문을 사용할 수 있다.</li>
<li><code>collections.deque(maxlen=cacheSize)</code></li>
</ul>
<pre><code class="language-python">def solution(cacheSize, cities):
    import collections
    cache = collections.deque(maxlen=cacheSize)
    answer = 0
    for city in cities:
        c = city.lower()
        if c in cache:
            answer += 1
            cache.remove(c)
            cache.append(c)
        else:
            answer += 5
            cache.append(c)
    return answer</code></pre>
<pre><code class="language-python">deque([&#39;pangyo&#39;, &#39;seoul&#39;, &#39;newyork&#39;], maxlen=3)

인 상태에서 &#39;LA&#39; 차례가 된다면, 아래와 같이 cache 가 업데이트 된다. 

deque([&#39;seoul&#39;, &#39;newyork&#39;, &#39;la&#39;], maxlen=3) # &#39;la&#39;가 append 되면서, 제일 앞에 있던 &#39;pangyo&#39;가 삭제됨. </code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 스킬트리]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EC%8A%A4%ED%82%AC%ED%8A%B8%EB%A6%AC</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EC%8A%A4%ED%82%AC%ED%8A%B8%EB%A6%AC</guid>
            <pubDate>Sat, 13 Aug 2022 13:04:01 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/49993">코딩테스트 연습 &gt; 스킬트리</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ul>
<li><code>skill_trees</code> 를 하나씩 돌면서(<code>t</code>) 아래 조건을 만족할 때 answer 개수를 +1 하여 반환한다.</li>
</ul>
<ol>
<li><code>skill</code> 을 list 로 변환한 후(<code>list_skill</code>)</li>
<li><code>t</code> 의 현재 순서가 <code>list_skill</code> 에 포함되지 않거나, 포함된다면 0번째에 위치하여야 한다. </li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(skill, skill_trees):
    answer = 0
    for tree in skill_trees:
        success = True
        list_skill = list(skill)
        for t in tree:
            if t in list_skill:
                if t != list_skill.pop(0):
                    success = False
                    break
        if success:
            answer += 1
    return answer</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ul>
<li>다른 사람들의 풀이를 보면서 많이 배운 문제다.</li>
</ul>
<ol>
<li><code>for-else</code> 문: flag <code>success</code> 변수를 없앨 수 있다.</li>
</ol>
<p>for문 중간에 break 로 빠져나올 때가 있다. 
break 문으로 빠져나오지 않았다면 <code>for-else</code> 문의 <code>else</code> 문으로 들어가게 된다.</p>
<ol start="2">
<li><p>개선된 코드</p>
<pre><code class="language-python">def solution(skill, skill_trees):
 answer = 0
 for tree in skill_trees:
     list_skill = list(skill)
     for t in tree:
         if t in list_skill:
             if t != list_skill.pop(0):
                 break
     else:
         answer += 1
 return answer</code></pre>
</li>
<li><p><code>list</code> 대신 <code>deque</code> 을 사용할 수 있다: <code>deque.popleft()</code></p>
</li>
</ol>
<pre><code class="language-python">import collections

def solution(skill, skill_trees):
    answer = 0
    for tree in skill_trees:
        deque = collections.deque(skill)
        for t in tree:
            if t in deque:
                if t != deque.popleft():
                    break
        else:
            answer += 1
    return answer</code></pre>
<ol start="4">
<li><code>string</code> to <code>char(string) list</code></li>
</ol>
<pre><code class="language-python">str = &quot;CBD&quot;

list(str) # [&#39;C&#39;, &#39;B&#39;, &#39;D&#39;]</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 멀리 뛰기]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EB%A9%80%EB%A6%AC-%EB%9B%B0%EA%B8%B0</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EB%A9%80%EB%A6%AC-%EB%9B%B0%EA%B8%B0</guid>
            <pubDate>Tue, 09 Aug 2022 14:09:40 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12914">코딩테스트 연습 &gt; 멀리 뛰기</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>한 번에 1칸 또는 2칸만 오를 수 있다. 
따라서, <code>memo[i]</code> (<code>i</code>번째 칸을 오를 수 있는 방법의 수) 는 <code>memo[i-1]</code> (<code>i-1</code> 번째 칸까지 올라올 수 있는 경우의 수) + <code>memo[i-2]</code>(<code>i-2</code> 번째 칸까지 올라올 수 있는 경우의 수) 이다. </p>
<ul>
<li><code>i-1</code> 번째에서 <strong>1칸</strong>을 오르거나 <code>i-2</code> 번째 칸에서 <strong>2칸</strong>을 올라올 수 있다.</li>
</ul>
</li>
<li><p>전형적인 DP 문제로 풀 수 있다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(n):
    if n == 1:
        return 1

    memo = [0] * n
    memo[0] = 1
    memo[1] = 2

    for i in range(2, n):
        memo[i] = (memo[i-1] + memo[i-2]) % 1234567

    return memo[n-1] </code></pre>
<h4 id="kotlin">kotlin</h4>
<pre><code class="language-kotlin">fun solution(n: Int): Long {
    if (n == 1) return 1

    val memo = LongArray(n)
    memo[0] = 1L
    memo[1] = 2L

    for (i in 2 until n) {
        memo[i] = (memo[i-1] + memo[i-2]) % 1234567
    }

    return memo[n-1]
}</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li><code>n</code> 이 1인 경우에 대한 예외처리</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 오픈채팅방]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EC%98%A4%ED%94%88%EC%B1%84%ED%8C%85%EB%B0%A9</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EC%98%A4%ED%94%88%EC%B1%84%ED%8C%85%EB%B0%A9</guid>
            <pubDate>Mon, 08 Aug 2022 14:06:19 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/42888">코딩테스트 연습 &gt; 오픈채팅방</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<h4 id="python">python</h4>
<ol>
<li><p><code>record</code> 를 split() 하여 0번째 값이 각각 <code>Enter</code> or <code>Leave</code> 일 때와 <code>Enter</code> or <code>Change</code> 일 때 아래 로직을 수행한다.</p>
<ul>
<li><code>Enter</code> or <code>Leave</code>    : <code>orders</code> 에 &lt;첫 단어, ID&gt; 를 추가</li>
<li><code>Enter</code> or <code>Change</code>    : <code>dic[ID] = 닉네임</code> 업데이트</li>
</ul>
</li>
<li><p><code>orders</code>를 돌면서 <code>answer</code> 리스트에 첫 단어가 <code>Enter</code> 일 때는 &quot;<code>dic[유저 ID] (== 최종 닉네임)</code> 님이 들어왔습니다.&quot;, 
<code>Leave</code> 일 때는 &quot;~~님이 나갔습니다.&quot; 를 리스트에 추가하여 반환한다.</p>
</li>
</ol>
<h4 id="kotlin">kotlin</h4>
<ol>
<li><p><code>record</code> 를 split() 하고,  0번째 값이 각각 <code>Enter</code>,<code>Leave</code>,<code>Change</code> 일 때 아래 로직을 수행한다.</p>
<ul>
<li><code>Enter</code>    : <code>map[ID] = 닉네임</code> 업데이트, <code>answer</code> 리스트에 <code>[ID] 들어왔습니다.</code> 추가</li>
<li><code>Leave</code>     : <code>answer</code> 리스트에 <code>[ID] 나갔습니다.</code> 추가</li>
<li><code>Change</code>    : <code>map[ID] = 닉네임</code> 업데이트</li>
</ul>
</li>
<li><p><code>answer</code>를 돌면서 각 아이템을 split() 하여 <code>map[&lt;0번째 아이템&gt;]님이 &lt;1번째 아이템&gt;</code> 로 변환한 후 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python-1">python</h4>
<pre><code class="language-python">def solution(record):
    answer = []
    dic = {}
    orders = []

    for r in record:
        list = r.split()
        if list[0] == &#39;Enter&#39; or list[0] == &#39;Leave&#39;:
            orders.append([list[0], list[1]])
        if list[0] == &#39;Enter&#39; or list[0] == &#39;Change&#39;:
            dic[list[1]] = list[2]

    for order in orders:
        if order[0] == &#39;Enter&#39;:
            answer.append(dic[order[1]] + &quot;님이 들어왔습니다.&quot;)
        else:
            answer.append(dic[order[1]] + &quot;님이 나갔습니다.&quot;)

    return answer</code></pre>
<h4 id="kotlin-1">kotlin</h4>
<pre><code class="language-kotlin">fun solution(record: Array&lt;String&gt;): Array&lt;String&gt; {
    val answer = mutableListOf&lt;String&gt;()
    val map = HashMap&lt;String, String&gt;() // &lt;ID, 닉네임&gt;

    record.forEach { r -&gt;
        val input = r.split(&quot; &quot;)
        val id = input[1]
        when(input[0]) {
            &quot;Enter&quot; -&gt; {
                map[id] = input[2]
                answer.add(&quot;$id 들어왔습니다.&quot;)
            }
            &quot;Leave&quot; -&gt; answer.add(&quot;$id 나갔습니다.&quot;)
            &quot;Change&quot; -&gt; map[id] = input[2]
        }
    }

    return answer.map { str -&gt;
        &quot;${map[str.split(&quot; &quot;)[0]]}님이 ${str.split(&quot; &quot;)[1]}&quot;
    }.toTypedArray()
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 짝지어 제거하기]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EC%A7%9D%EC%A7%80%EC%96%B4-%EC%A0%9C%EA%B1%B0%ED%95%98%EA%B8%B0-aqku45e3</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EC%A7%9D%EC%A7%80%EC%96%B4-%EC%A0%9C%EA%B1%B0%ED%95%98%EA%B8%B0-aqku45e3</guid>
            <pubDate>Sun, 07 Aug 2022 13:44:48 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12973">코딩테스트 연습 &gt; 짝지어 제거하기</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>stack 변수를 정의하고, <code>s</code> 를 하나씩 for문 돌면서</p>
</li>
<li><p>stack이 비어있거나 stack의 마지막 아이템과 현재 값이 다르면 stack 에 현재 값을 추가하고</p>
</li>
<li><p>stack의 마지막 아이템과 현재 값이 같다면, stack의 마지막 아이템을 pop() 한다.</p>
</li>
<li><p>stack이 비어있으면 1, 비어있지 않다면 0을 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(s):
    stack = []    
    for c in s:
        if len(stack) == 0:
            stack.append(c)
        else:
            if c == stack[-1]:
                stack.pop()
            else:
                stack.append(c)
    if stack:
        return 0
    else:
        return 1</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li><code>Stack</code>을 활용해야 하는 문제라는 것을 인지하기까지 시간이 걸려서 아쉬웠던 문제. 입력 문자열의 길이가 최대 1,000,000 임에도 앞에서부터 차례로 현재 index와 다음 index의 값이 같으면 <code>pop()</code> 하는 방법을 시도했었다. (<code>current</code>) 결과는 일부 테스트케이스 시간초과 Fail 이었다.</li>
</ol>
<pre><code class="language-python">def solution(s): # 시간초과
    current = s
    count = 0
    while True:
        if current == &#39;&#39;:
            return 1

        result = &#39;&#39;
        count = 0
        i = 0
        while i &lt; len(current):
            if i &lt; len(current) - 1 and current[i] == current[i+1]:
                i += 2
                count += 1
            else:
                result += current[i]
                i += 1
        current = result

        if count == 0:
            return 0
    return 0</code></pre>
<p>비슷한 문제 (<code>같은 문자일 때 삭제</code> 등)를 다시 만난다면, 또는 입력 값이 커서 위와 같은 탐색방법으로 문제가 풀리지 않는다면
<code>stack</code>, <code>queue</code> 등 자료구조를 하나씩 떠올리며 사용할 수 있을지 점검해 봐야겠다.</p>
<ol start="2">
<li>리스트가 비어있는지 검사: <code>if not list:</code><pre><code class="language-python">if stack:         # 으로 stack 이 비어있지 않음을 검사한 거 처럼
</code></pre>
</li>
</ol>
<p>if not stack:     # stack 이 비어있음을 검사한다.</p>
<pre><code></code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 2 x n 타일링]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-2-x-n-%ED%83%80%EC%9D%BC%EB%A7%81</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-2-x-n-%ED%83%80%EC%9D%BC%EB%A7%81</guid>
            <pubDate>Sun, 07 Aug 2022 10:39:29 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12900">코딩테스트 연습 &gt; 2 x n 타일링</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<p>n=1 부터 하나씩 n 을 늘려가면서 규칙을 찾아본다.</p>
<pre><code>n = 1     1

n = 2    2

n = 3    3    &lt;-- n=1 + n=2

n = 4    5    &lt;-- n=2 + n=3

n = 5    8    &lt;-- n=3 + n=4</code></pre><p>그림을 그려서 보면, N 번째 경우 세로 1칸 + (N-1)칸, 가로 2칸 + (N-2)칸으로 나타내 볼 수 있다.</p>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(n):
    list = [1, 2]
    for i in range(2, n):
        list.append((list[i-2] + list[i-1]) % 1000000007)
    return list[n-1]</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<p>주어진 내용 안에서 최대한의 규칙을 찾아본다. 그림을 그려서 보면 더 좋다.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 소수 찾기]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EC%86%8C%EC%88%98-%EC%B0%BE%EA%B8%B0</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EC%86%8C%EC%88%98-%EC%B0%BE%EA%B8%B0</guid>
            <pubDate>Sun, 07 Aug 2022 10:21:06 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/42839">코딩테스트 연습 &gt; 소수 찾기</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<pre><code class="language-python">from itertools import permutations

def solution(numbers):
    result = []
    for i in range(1, len(numbers)+1):
        for tp in permutations(numbers, i):
            num = int(&#39;&#39;.join(map(str, tp)))
            if is_prime(num):
                result.append(num)
    return len(set(result))


def is_prime(n):
    if n &lt; 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<h4 id="python">python</h4>
<ol>
<li>순열을 구해주는 라이브러리를 알게 되었다: <code>from itertools import permutations</code><pre><code class="language-python">from itertools import permutations
</code></pre>
</li>
</ol>
<p>permutation(list, n) # list 를 n개씩 묶어주는 리스트를 반환</p>
<p>```</p>
<p><a href="https://velog.io/@insutance/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4Python-%EC%86%8C%EC%88%98-%EC%B0%BE%EA%B8%B0">참고</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 피보나치 수]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%ED%94%BC%EB%B3%B4%EB%82%98%EC%B9%98-%EC%88%98</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%ED%94%BC%EB%B3%B4%EB%82%98%EC%B9%98-%EC%88%98</guid>
            <pubDate>Sun, 07 Aug 2022 05:11:42 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12945">코딩테스트 연습 &gt; 피보나치 수</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><code>memo</code> 리스트에 계산 결괏값을 저장한 후, <code>memo[n]</code> 을 반환한다.<ul>
<li>리스트 변수 저장 없이 재귀함수를 사용하면 메모리 초과 실패가 발생한다.</li>
</ul>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python"> def solution(n):
    memo = [0, 1]
    for i in range(2, n+2):
        memo.append((memo[i-1] + memo[i-2]) % 1234567)
    return memo[n] </code></pre>
<h4 id="kotlin">kotlin</h4>
<pre><code class="language-kotlin">fun solution(n: Int): Int {
   val memo = IntArray(n + 1)
   for (i in 0..n) {
       when (i) {
           0 -&gt; memo[0] = 0
           1 -&gt; memo[1] = 1
           else -&gt; memo[i] = (memo[i - 1] + memo[i - 2]) % 1234567
       }
   }
   return memo[n]
}</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li>저장된 값을 12345로 나눈 나머지를 반환해야하는 문제일 때, 
저장하는 시점부터 12345로 나눈 나머지 값을 저장할 수 있다.</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 최댓값과 최솟값]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EC%B5%9C%EB%8C%93%EA%B0%92%EA%B3%BC-%EC%B5%9C%EC%86%9F%EA%B0%92-57ujlwby</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EC%B5%9C%EB%8C%93%EA%B0%92%EA%B3%BC-%EC%B5%9C%EC%86%9F%EA%B0%92-57ujlwby</guid>
            <pubDate>Sun, 07 Aug 2022 04:57:46 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12939">코딩테스트 연습 &gt; 최댓값과 최솟값</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>두 배열에서 숫자를 하나씩 골라 두 수를 곱한 값의 누적 합이 최솟값을 갖도록 구하는 문제다.</p>
</li>
<li><p>한 배열의 최솟값과 다른 배열의 최댓값을 차례로 계산한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(A,B):
    answer = 0
    A.sort()
    B.sort(reverse = True)
    for i in range(len(A)):
        answer += A[i] * B[i]
    return answer    </code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ul>
<li>두 배열의 <code>곱한 값의 누적 합의 최솟값</code>은 각 배열의 최솟값 최댓값을 곱해주어 구할 수 있다.</li>
</ul>
<h4 id="python-1">python</h4>
<ol>
<li>한 줄 코드: <code>sum()</code>, <code>zip()</code><pre><code class="language-python">def solution(A,B):
 return sum(a*b for a, b in zip(sorted(A), sorted(B, reverse=True)))</code></pre>
</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 최댓값과 최솟값]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EC%B5%9C%EB%8C%93%EA%B0%92%EA%B3%BC-%EC%B5%9C%EC%86%9F%EA%B0%92</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EC%B5%9C%EB%8C%93%EA%B0%92%EA%B3%BC-%EC%B5%9C%EC%86%9F%EA%B0%92</guid>
            <pubDate>Sun, 07 Aug 2022 04:00:03 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12939">코딩테스트 연습 &gt; 최댓값과 최솟값</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p><code>s</code>를 &quot; &quot; 기준으로 split() 한 후에 리스트 아이템을 int 형으로 변환한다.</p>
</li>
<li><p>int list 중에서 최솟값과 최댓값을 string으로 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(s):
    value = list(map(int, s.split()))
    return &quot; &quot;.join([str(min(value)), str(max(value))])</code></pre>
<h4 id="kotlin">kotlin</h4>
<pre><code>fun solution(s: String): String =
    s.split(&quot; &quot;).map { c -&gt;
        c.toInt()
    }.run {
        return &quot;${minOf { it }} ${maxOf { it }}&quot;
    }</code></pre><h3 id="3-배운점">3. 배운점</h3>
<h4 id="python-1">python</h4>
<ol>
<li>string list to int list: <code>list(map(int, str_list))</code></li>
</ol>
<ul>
<li><a href="https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int">convert-all-strings-in-a-list-to-int</a></li>
</ul>
<ol start="2">
<li>kotlin의 <code>&quot;${value1} ${value2}&quot;</code> == <code>str(value1) + &quot; &quot; + str(value2)</code></li>
</ol>
<pre><code class="language-kotlin"># asis
&quot; &quot;.join([str(min(value)), str(max(value))])

# tobe
str(min(value)) + &quot; &quot; + str(max(value))
``</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 더 맵게]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EB%8D%94-%EB%A7%B5%EA%B2%8C</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EB%8D%94-%EB%A7%B5%EA%B2%8C</guid>
            <pubDate>Sun, 07 Aug 2022 03:41:09 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/42626">코딩테스트 연습 &gt; 더 맵게</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>최솟값을 계속해서 얻어야 하는 문제기 때문에 <code>min heap</code>을 사용한다.</p>
</li>
<li><p><code>모든 음식의 스코빌 지수를 K 이상으로 만들 수 없는 경우</code> 가 언제일지를 고민해봐야 한다.</p>
<ul>
<li><p>가장 맵지 않은 음식(<code>a</code>)과 두 번째로 맵지 않은 음식(<code>b</code>) <strong>2개</strong>의 아이템을 <code>heap</code> 에서 pop 하여 <code>a+b*2</code>로 계산한 새로운 <strong>1개</strong>의 아이템을 <code>heap</code> 에 넣게 된다. 즉, <strong>heap 아이템 수가 1개씩 줄어든다.</strong></p>
</li>
<li><p>while문은 heap 의 최솟값이 K 미만일 때 계속 돌게 되는데, heap 의 개수가 1개이면서 최솟값이 K 미만일 때 모든 음식의 스코빌 지수를 K 이상으로 만들 수 없는 케이스가 된다.</p>
</li>
</ul>
</li>
<li><p>while 문을 1번 돌 때마다 count 를 더하여 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<pre><code class="language-python">import heapq

def solution(scoville, K):
    heap = []
    answer = 0
    for s in scoville:
        heapq.heappush(heap, s)

    while heap[0] &lt; K:
        if len(heap) == 1:
            return -1
        mixed = heapq.heappop(heap) + heapq.heappop(heap) * 2
        heapq.heappush(heap, mixed)
        answer += 1
    return answer</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li>Heap (힙)</li>
</ol>
<ul>
<li>힙은 완전이진트리로 최솟값과 최댓값을 찾는 연산을 빠르게 수행할 수 있다.<ul>
<li><code>Min Heap</code>: 부모 키값이 자식 노트 키값보다 항상 작음 (&lt;-&gt; <code>Max Heap</code>)</li>
<li>형제 노드 사이에 대소 관계 규칙 없음</li>
</ul>
</li>
</ul>
<ol start="2">
<li>Heap 사용법<pre><code class="language-python">import heapq
</code></pre>
</li>
</ol>
<p>heap = [] # default: Min Heap</p>
<p>heapq.heappush(heap, item)  # push
heapq.heappop(heap)            # pop
heap[idx]                    # 조회</p>
<h1 id="max-heap">Max Heap</h1>
<p>heapq.heappush(heap, (-item, item)) # (priority, value)</p>
<pre><code>

</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 영어 끝말잇기]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EC%98%81%EC%96%B4-%EB%81%9D%EB%A7%90%EC%9E%87%EA%B8%B0</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EC%98%81%EC%96%B4-%EB%81%9D%EB%A7%90%EC%9E%87%EA%B8%B0</guid>
            <pubDate>Sat, 06 Aug 2022 14:02:58 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12981">코딩테스트 연습 &gt; 영어 끝말잇기</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p><code>words</code> 를 for 문을 돌면서
이전에 나왔던 단어이거나, 직전 알파벳과 현재 처음 알파벳이 다르거나, 단어의 개수가 1인 경우에
[번호, 순서]를 반환한다.</p>
</li>
<li><p>위의 3가지 경우에 포함되지 않는다면 [0,0] 을 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<pre><code class="language-python">def solution(n, words):
    list = []
    last_c = &#39;&#39;
    for i, word in enumerate(words):
        if (word in list) or (last_c != &#39;&#39; and last_c != word[0]) or len(word) == 1:
            return [i%n+1, i//n+1]
        list.append(word)
        last_c = word[-1]
    return [0,0]</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li><p><code>last_c</code> 로 직전 마지막 알파벳을 저장해서 다음번 for 문에 이용할 수 있다.</p>
</li>
<li><p>입력 parameter를 print 해보면서 로직과 반환 값에 대해 생각해본다: 번호<code>i%n+1</code>, 순서<code>i//n+1</code></p>
</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. N개의 최소공배수]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-N%EA%B0%9C%EC%9D%98-%EC%B5%9C%EC%86%8C%EA%B3%B5%EB%B0%B0%EC%88%98</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-N%EA%B0%9C%EC%9D%98-%EC%B5%9C%EC%86%8C%EA%B3%B5%EB%B0%B0%EC%88%98</guid>
            <pubDate>Sat, 06 Aug 2022 09:36:14 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12953">코딩테스트 연습 &gt; N개의 최소공배수</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p><code>lcm</code> 을 1로 초기화 한다.</p>
</li>
<li><p><code>arr</code> 를 for 문 돌면서, <code>lcm</code> 과 현재 숫자의 <code>lcm</code> 을 구하여 업데이트 한다.</p>
</li>
<li><p><code>lcm</code> 을 반환한다.</p>
</li>
</ol>
<pre><code>arr: 2 6 8 14
                lcm
2                2
2 * 3            2 * 3
2 * 2 * 2        2 * 2 * 2 * 3
2 * 7            2 * 2 * 2 * 3 * 7
</code></pre><h3 id="2-나의-풀이">2. 나의 풀이</h3>
<h4 id="python">python</h4>
<pre><code class="language-python">def solution(arr):
    size = len(arr)
    lcm = 1
    for n in arr:
        lcm = lcm * n  / gcd(lcm, n)
    return lcm

def gcd(a, b):
    if a % b == 0:
        return b
    return gcd(b, a % b)</code></pre>
<h4 id="kotlin">kotlin</h4>
<pre><code class="language-kotlin">fun solution(arr: IntArray): Int =
    arr.fold(1) { lcm, n -&gt;
        lcm * n / gcd(lcm, n)
    }

fun gcd(a: Int, b: Int): Int {
    if (a % b == 0) return b
    return gcd(b, a % b)
}</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li>최대공약소, 최소공배수: <a href="https://velog.io/@dev-eunji/Lv1.-%EC%B5%9C%EB%8C%80%EA%B3%B5%EC%95%BD%EC%88%98%EC%99%80-%EC%B5%9C%EC%86%8C%EA%B3%B5%EB%B0%B0%EC%88%98">참고문제</a></li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 땅따먹기]]></title>
            <link>https://velog.io/@dev-eunji/Lv2.-%EB%95%85%EB%94%B0%EB%A8%B9%EA%B8%B0</link>
            <guid>https://velog.io/@dev-eunji/Lv2.-%EB%95%85%EB%94%B0%EB%A8%B9%EA%B8%B0</guid>
            <pubDate>Sat, 06 Aug 2022 09:01:46 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/12913">코딩테스트 연습 &gt; 땅따먹기</a></p>
</blockquote>
<h3 id="1-풀이-설명">1. 풀이 설명</h3>
<ol>
<li><p>2번째 row부터 for 문을 돌면서 이전 row 중 현재 col과 다르고, 가장 큰 값을 <code>land[i][j]</code> 에 더한다.</p>
</li>
<li><p>마지막 row 의 값 중 가장 큰 값을 반환한다.</p>
</li>
</ol>
<h3 id="2-나의-풀이">2. 나의 풀이</h3>
<pre><code class="language-python">def solution(land):
    for i in range(1, len(land)):
        for j in range(4):
            land[i][j] += max(land[i-1][k] for k in range(4) if k != j)
    return max(land[-1])</code></pre>
<h3 id="3-배운점">3. 배운점</h3>
<ol>
<li>이전 값을 활용해서 현재 값 (<code>land[i][j]</code>)을 업데이트 하는 방법</li>
</ol>
<ul>
<li>이전 row 중 최대 값 <pre><code class="language-kotlin">max(land[i-1][k] for k in range(4))</code></pre>
</li>
</ul>
]]></description>
        </item>
    </channel>
</rss>