본문 바로가기
파이썬 코딩테스트/해커랭크

HackerRank / Sherlock and Cost / Python

by S.T.Lee 2021. 12. 24.

 

https://www.hackerrank.com/challenges/sherlock-and-cost/problem?isFullScreen=true

 

Sherlock and Cost | HackerRank

Sherlock and Cost | HackerRank We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

www.hackerrank.com

 

import math
import os
import random
import re
import sys

    
def cost(B):
    maxi, max1 = 0, 0
    #maxi는 B[i]번째까지의 List가 B[i]인 상태로 끝날때 합
    #max1는 B[i]번째까지의 List가 1인 상태로 끝날때 합
    for i in range(1,len(B)):
        curr, prev = B[i], B[i-1]
        new_maxi = max(maxi + abs(curr - prev), max1 + (curr - 1))
        #전에 값이 1 또는 원래 값일때의 차이 중 큰 값을 선택
        new_max1 = max(maxi + abs(1 - prev), max1)
        #전애 값이 1(1-1=0이므로 max1 그 상태 그대로) 또는 원래 값일때의 차이 중 큰 값을 선택
        maxi, max1 = new_maxi, new_max1    
    return max(maxi, max1)
    

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input().strip())

    for t_itr in range(t):
        n = int(input().strip())

        B = list(map(int, input().rstrip().split()))

        result = cost(B)

        fptr.write(str(result) + '\n')

    fptr.close()