[LeetCode] 2574. Left and Right Sum Differences (Python)
python, algorithms, array, prefix-sum
Tags: algorithms, array, prefix-sum, python
Categories: LeetCode
- Reference
left_sum,right_sumλ°°μ΄μ λ§λ€μ§ λ§κ³ λ°λ‘λ°λ‘ μ²λ¦¬νλ©΄ λ μ’μΌλ €λ?- λ€λ₯Έ μ¬λλ€ νμ΄ λ³΄λ λμ²λΌ νΌ μ¬λμ λ¨ νλͺ
λ μμλ€..
- λ΄κ° μκ°ν΄λ μ’ λ³΅μ‘ν νμ΄ γ γ
- Runtime
71ms - Beats
83.96%
Solution
from typing import List
class Solution:
# nums: [10, 4, 8, 3]
# left: [0, 0 + 10, 0 + 10 + 4, 0 + 10 + 4 + 8] = [0, 10, 14, 22] -> 4λ²λ§ νκ³ μ€λ¨
# right: [0 + 3 + 8 + 4, 0 + 3 + 8, 0 + 3, 0] = [15, 11, 3, 0] -> 4λ²λ§ νκ³ μ€λ¨
def leftRigthDifference(self, nums: List[int]) -> List[int]:
left_sum = [0] * len(nums)
right_sum = [0] * len(nums)
left = 0
right = 0
for i in range(1, len(nums)):
left += nums[i - 1]
left_sum[i] = left
for i in range(len(nums) - 2, -1, -1):
right += nums[i + 1]
right_sum[i] = right
# λ°°μ΄ μμλ³λ‘ λΉΌμ£Όκ³ μ λκ°
return list(abs(x - y) for x, y in zip(left_sum, right_sum))
print(Solution().leftRigthDifference([10, 4, 8, 3]))
Leave a comment