Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 12. 4. 23:45

https://leetcode.com/problems/minimum-average-difference/

 

Minimum Average Difference - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

prefix sum optimized 를 활용!

class Solution:
    def minimumAverageDifference(self, nums: List[int]) -> int:
        n = len(nums)
        ans = -1
        mad = math.inf
        cps = 0
        
        s = 0
        
        for index in range(n):
            s += nums[index]
        
        for index in range(n):
            cps += nums[index]
            lpa = cps
            lpa //= (index + 1)
            
            rpa = s - cps
            if index != n-1:
                rpa //= (n-index-1)
            
            cd = abs(lpa - rpa)
            
            if cd < mad:
                mad = cd
                ans = index
        
        return ans
반응형