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

HackerRank / Sherlock and Array / Python

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

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

 

Sherlock and Array | HackerRank

Check whether there exists an element in the array such that sum of elements on its left is equal to the sum of elements on its right.

www.hackerrank.com

def balancedSums(arr):
  for i in range(len(arr)):
          if i == 0:
              left = 0
              right = sum(arr[i+1:])
              if left == right:
                  return 'YES'
          elif i == len(arr):
              left = sum(arr[:i])
              right = 0
              if left == right:
                  return 'YES'
          else:
              left = sum(arr[:i])
              right = sum(arr[i+1:])
              if left == right:
                  return 'YES'

테스트 케이스에서 시간 초과

아마 슬라이싱 때문인듯

 

def balancedSums(arr):
  if len(arr) == 1:
          return 'YES'
      left = 0
      right = sum(arr[1:])
      for i in range(len(arr)-1):
          if left == right:
              return "YES"
          else:
              left += arr[i]
              right -= arr[i+1]

통과는 했으나 서순이 마음에 들지 않음

 

def balancedSums(arr):
    # Write your code here
    right = sum(arr)
    left = 0
    for i in range(len(arr)):
        right = right - arr[i]
        if left == right:
            return "YES"
        left += arr[i]
    return "NO"

깔끔