[2256] Minimum Average Difference | Biweekly Contest 77 Medium

yoongyum·2022년 5월 5일
0

코딩테스트 🧩

목록 보기
33/47
post-thumbnail

🔎 문제설명

You are given a 0-indexed integer array nums of length n.

The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.

Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.

Example 1

Input: nums = [2,5,3,9,5,3]
Output: 3
Explanation:
- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.
- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.
- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.
- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.
- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.
- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.
The average difference of index 3 is the minimum average difference so return 3.

Example 2

Input: nums = [0]
Output: 0
Explanation:
The only index is 0 so return 0.
The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.

제한사항

  • 1 ≤ nums.length ≤ 10510^5
  • 0 ≤ nums[i] ≤ 10510^5



제한 조건 때문에 2중 for문 못쓰는 문제입니다.

이 문제를 맞추긴 했는 데 for문 하나로 어떻게 풀어야 하는지 생각하느라 좀 오래걸렸습니다.

🧊 파이썬 코드

class Solution:
    def minimumAverageDifference(self, nums: List[int]) -> int:
        allSum =0 # 총 수
        for num in nums:
            allSum += num
            
        minAvgDif = 50001
        answer = 0
        sum = 0
        for i,num in enumerate(nums):
            sum += num
            dif = int(sum/(i+1)) 
            if i == len(nums)-1:
                dif2=0
            else : dif2 = int((allSum-sum)/(len(nums)-(i+1)))
            if minAvgDif >  abs(dif -dif2):
                answer = i
                minAvgDif = min(abs(dif -dif2),minAvgDif)
                
        return answer

0개의 댓글