Altiora Petamus

Tape Equilibrium ๋ณธ๋ฌธ

1day-1algorithm

Tape Equilibrium

Haril Song 2021. 7. 1. 20:28
 

TapeEquilibrium coding task - Learn to Code - Codility

Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|.

app.codility.com

๐Ÿค”์ƒ๊ฐํ•ด๋ณด๊ธฐ

๋ฌธ์ œ ๊ทธ๋Œ€๋กœ ๋‹จ์ˆœํžˆ ๋ฐฐ์—ด์„ slice ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ’€์—ˆ๋”๋‹ˆ ์‹œ๊ฐ„๋ณต์žก๋„ ๋ฌธ์ œ๋ผ ๊ทธ๋Ÿฐ์ง€ ์ ์ˆ˜๊ฐ€ ์•„์ฃผ ์งœ๊ฒŒ ๋‚˜์™”๋‹ค.

๊ทธ๋ž˜์„œ Dynamic programming ์œผ๋กœ ํ’€์–ด๋ณด์•˜๋‹ค.

  • ํ•ฉ์„ ์ €์žฅํ•ด๊ฐ€๋Š” ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด๋‘”๋‹ค.
  • ๊ทธ ๋ฐฐ์—ด์—์„œ ํ•˜๋‚˜์”ฉ ๊บผ๋‚ด์„œ ์—ฐ์‚ฐ์„ ์ง„ํ–‰ํ•˜๋ฉด, ๋‹ค์‹œ ์ฒ˜์Œ๋ถ€ํ„ฐ ํ•ฉ์„ ๊ตฌํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.

์ฒซ๋ฒˆ์งธ ํ’€์ด - Total score 61%

def solution(A):
    result = 0
    dp = [0] * (len(A) - 1)
    dp[0] = A[0]

    for i in range(1, len(A) - 1):
        dp[i] = dp[i - 1] + A[i]

    a = sum(A)
    for j in dp:
        abs1 = abs((a - j) - j)
        if result == 0 or result > abs1:
            result = abs1

    return result

์–ด๋”˜๊ฐ€ ์˜ˆ์™ธ ์š”์†Œ๊ฐ€ ์žˆ์—ˆ๋Š”์ง€ ์ „์ฒด์ ์œผ๋กœ ์ ์ˆ˜๊ฐ€ ๋งŒ์กฑ์Šค๋Ÿฝ์ง€ ๋ชปํ–ˆ๋‹ค.

์ •ํ™•ํ•˜์ง„ ์•Š์ง€๋งŒ ์˜ˆ์ƒ๋˜๋Š” ๋ถ€๋ถ„์€ result = 0 ์ด๋ผ๊ณ  ์ดˆ๊ธฐํ™”ํ•˜๊ณ  ์กฐ๊ฑด๋ฌธ์„ ์ง„ํ–‰ํ•  ๋•Œ ์ œ๋Œ€๋กœ ๊ฐ’์ด ๋ฐ˜์˜์ด ์•ˆ๋˜๋Š” ๊ฒƒ์œผ๋กœ ๋ณด์˜€๋‹ค.

์กฐ๊ธˆ ๋” ์ •ํ™•ํ•˜๊ฒŒ ๋™์ž‘ํ•˜๋„๋ก ์ฝ”๋“œ๋ฅผ ๊ณ ์ณ๋ดค๋‹ค.

๋‘๋ฒˆ์งธ ํ’€์ด - Total Score 100%

def solution(A):
    result = []
    s = sum(A)
    t = [0] * (len(A) - 1)
    dp = [0] * (len(A) - 1)
    dp[0] = A[0]
    t[0] = s - dp[0]

    for i in range(1, len(A) - 1):
        dp[i] = dp[i - 1] + A[i]
        t[i] = s - dp[i]

    for i in range(len(dp)):
        result.append(abs(dp[i] - t[i]))

    return min(result)

min() ์„ ์‚ฌ์šฉํ•ด์„œ ์ตœ์†Œ๊ฐ’์„ ๋ฆฌํ„ดํ•ด์ฃผ๋Š” ๋ฐฉ์‹์ด๋ผ ์ ์ˆ˜๋ฅผ ์งœ๊ฒŒ ์ค„๊ฑฐ๋ผ ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, ์ด ์ •๋„๋Š” ํ—ˆ์šฉ๋˜๋Š” ๋ฒ”์œ„ ์•ˆ์ธ๊ฐ€๋ณด๋‹ค. ์ตœ์•…์˜ ๊ฒฝ์šฐ ์•ฝ 100,000๊ฐœ๋ฅผ ๊ฒ€์‚ฌํ• ํ…๋ฐ O(N)์„ ๋งŒ์กฑํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด ํ†ต๊ณผ๋ผ ๋ณด์—ฌ์ง„๋‹ค.