253. TapeEquilibrium

아현·2021년 8월 14일
0

Algorithm

목록 보기
265/400
post-custom-banner



1. JavaScript


function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)
    const N = A.length;
    const totalSum = A.reduce((a, b) => a + b);
    let leftSum = A[0];
    let rightSum = totalSum - A[0];
    let minDiff = Number.MAX_SAFE_INTEGER;
    let diff;

    for(let P=1; P<N; P++){
        diff = Math.abs(leftSum - rightSum);
        if(diff < minDiff){
            minDiff = diff;
        }
        leftSum += A[P];
        rightSum -= A[P];
    }

    return minDiff;
}





2. Python


def solution(A):
    sum_right = sum(A)
    sum_left = 0
    result = None 
    for i in range(len(A)-1):
        sum_right -= A[i]
        sum_left += A[i]
        
        if result == None: 
            result = abs(sum_right - sum_left)
        else: 
            result = min(result, abs(sum_right - sum_left))
            
    return result
profile
For the sake of someone who studies computer science
post-custom-banner

0개의 댓글