일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- leetcode
- 10분
- 읽기
- 링피트
- 스탭퍼
- 프로젝트
- 만화도
- FIT XR
- 쓰릴오브파이트
- 영어공부
- 영어원서읽기
- English
- 리얼 클래스
- 운동
- 파비최
- 사이드
- 뭐든
- Daily Challenge
- 화상영어
- 괜찮음
- 3줄정리
- Problem Solving
- realclass
- 잡생각
- Writing
- 미드시청
- 개발자
- 매일
- 월간
- 30분
Archives
- Today
- Total
파비의 매일매일 공부기록
2023.11.25 Today's Challenge 본문
https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/
Sum of Absolute Differences in a Sorted Array - LeetCode
Can you solve this real interview question? Sum of Absolute Differences in a Sorted Array - You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equ
leetcode.com
class Solution:
def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]:
n = len(nums)
prefix = [nums[0]]
for i in range(1, n):
prefix.append(prefix[-1] + nums[i])
ans = []
for i in range(len(nums)):
left_sum = prefix[i] - nums[i]
right_sum = prefix[-1] - prefix[i]
left_count = i
right_count = n - 1 - i
left_total = left_count * nums[i] - left_sum
right_total = right_sum - right_count * nums[i]
ans.append(left_total + right_total)
return ans
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
2023.11.27 Today's Challenge (0) | 2023.11.27 |
---|---|
2023.11.26 Today's Challenge (0) | 2023.11.26 |
2023.11.24 Today's Challenge (1) | 2023.11.24 |
2023.11.23 Today's Challenge (1) | 2023.11.23 |
2023.11.22 Today's Challenge (0) | 2023.11.22 |
Comments