본문 바로가기
Algorithm/LeetCode

[LeetCode] 1588 | Sum of All Odd Length Subarrays

by 밤초록 2022. 7. 5.
1588 | Sum of All Odd Length Subarrays
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/

 

 

 

작성 코드

 

class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        answer = 0
        for i in range(1, len(arr) + 1, 2):
            for start in range(len(arr) - i + 1):
                answer += sum(arr[start : start+i])
        return answer

 

 

접근 방법

 

  • 슬라이싱할 간격을 i 로 지정, 시작 값을 start 로 지정

 

 

 

이상 코드

 

class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        answer = 0
        len_arr = len(arr)
        for idx, num in enumerate(arr):
            answer += num * (((len_arr - idx) * (idx + 1) + 1) // 2)
        return answer

 

 

반응형

댓글