[LeetCode] 1551. Minimum Operations to Make Array Equal

Updated:

1551. Minimum Operations to Make Array Equal

n ์ด ์ฃผ์–ด์ง€๋ฉด ์ดˆํ•ญ์€ 1์ด๊ณ  ๋“ฑ์ฐจ๋Š” 2์ธ ๋“ฑ์ฐจ์ˆ˜์—ด์„ n ์˜ ๊ธธ์ด ๋งŒํผ ๋งŒ๋“ ๋‹ค.

์ด๋•Œ index ๋‘ ๊ฐœ๋ฅผ ๊ณจ๋ผ arr[x] -= 1, arr[y] += 1 ์„ ๋ฐ˜๋ณต ํ•ด ๋ฐฐ์—ด์˜ ๋ชจ๋“  ๊ฐ’์„ ๊ฐ™๊ฒŒ ๋งŒ๋“ค๋ฉด ๋œ๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด ๋ชจ๋“  ๊ฐ’์ด ๊ฐ™์•„ ์งˆ ๋•Œ, ๊ทธ ๊ฐ™์€ ๊ฐ’์„ ์–ด๋–ป๊ฒŒ ๊ตฌํ•˜๋ฉด ๋ ๊นŒ ? ๋ฐ”๋กœ ๋ฐฐ์—ด์˜ ํ‰๊ท  ๊ฐ’์ด ๊ทธ ๊ฐ’์ด ๋œ๋‹ค.

[1, 3, 5, 7, 9] ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค๋ฉด ๋”ํ•˜๊ธฐ 1, ๋นผ๊ธฐ 1 ์„ ํ†ตํ•ด ๋ชจ๋“  ๊ฐ’์„ ํ‰๊ท  ๊ฐ’์ธ 5๋กœ ๋งŒ๋“ค๋ฉด ๋œ๋‹ค.

๊ฒฐ๊ตญ ๋ฐฐ์—ด ์ค‘์—์„œ ํ‰๊ท  ๊ฐ’์—์„œ ํ‰๊ท  ๊ฐ’ ๋ณด๋‹ค ์ž‘์€ ๊ฐ’์„ ๋บ€ ์ˆ˜๋ฅผ ๋ชจ๋‘ ๋”ํ•˜๋ฉด ๋‹ต์ด ๋œ๋‹ค.

์œ„ ๋ฐฐ์—ด ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” (5 - 1) + (5 - 3) = 6 ์ด ๋œ๋‹ค.


class Solution:
	def minOperations(self, n: int) -> int:
		arr = [(2 * i) + 1 for i in range(n)]
		goal_num = n
		answer = 0

		for num in arr:
			if num < goal_num:
				answer += goal_num - num
			else:
				break

		return answer


test = Solution()
n = 5
print(test.minOperations(n))

Categories:

Updated:

Leave a comment