포스트

[Python] Programmer - Integer Triangle

DP method for calculating maximum cell sums, and integer triangle problem implementation in Python and Java

한국어 원문은 여기에서 볼 수 있습니다.
[Python] Programmer - Integer Triangle

Programmers Integer Triangle

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def solution(triangle):
    answer = 0
    
    for i in range(1, len(triangle)):
        for j in range(len(triangle[i])):
            if j == 0:
                triangle[i][j] += triangle[i-1][j]
            elif j == i:
                triangle[i][j] += triangle[i-1][j-1]
            else:
                triangle[i][j] += max(triangle[i-1][j-1], triangle[i-1][j])
    
    answer = max(triangle[-1])
    
    return answer

Dynamic Programming (DP)

A method of dividing a big problem into smaller problems and saving the answers to the smaller problems that have already been found to use them again.

  • How to save and reuse already obtained results without recalculating from scratch every time.

  • While solving the above problem using dynamic programming, change the meaning of triangle[i][j] to triangle[i][j] = 맨 위에서 이 칸까지 오는 최대 합 to find the ‘maximum sum that can be obtained when arriving at this cell.’

  • The same can be implemented in Java.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
      class Solution {
          public int solution(int[][] triangle) {
              for (int i = 1; i < triangle.length; i++) {
                  for (int j = 0; j < triangle[i].length; j++) {
    
                      if (j == 0) {
                          // 왼쪽 : 바로 위에서만 내려올  있음
                          triangle[i][j] += triangle[i - 1][j];
                      } 
                      else if (j == i) {
                          // 오른쪽 : 왼쪽 위에서만 내려올  있음
                          triangle[i][j] += triangle[i - 1][j - 1];
                      } 
                      else {
                          // 가운데: 왼쪽 , 오른쪽      선택
                          triangle[i][j] += Math.max(triangle[i - 1][j - 1], triangle[i - 1][j]);
                      }
                  }
              }
    
              int answer = 0;
    
              for (int i = 0; i < triangle[triangle.length - 1].length; i++) {
                  answer = Math.max(answer, triangle[triangle.length - 1][i]);
              }
    
              return answer;
          }
      }