3454. Minimum Operations to Make Array Equal to Target
My accepted Python solution to LeetCode problem 3454, Minimum Operations to Make Array Equal to Target, running in 67ms.
- Difficulty: Hard
- Python
- Runtime 67ms
- Memory 38MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 67ms, memory 38MB, accepted 2026-01-01.
class Solution:
def minimumOperations(self, nums: List[int], target: List[int]) -> int:
n = len(nums)
# Calculate difference array
diff = [target[i] - nums[i] for i in range(n)]
# Track positive and negative consecutive sums
result = 0
pos_sum = 0 # running positive sum
neg_sum = 0 # running negative sum (stored as positive)
for d in diff:
if d > 0:
# We need to increment
if d > pos_sum:
result += d - pos_sum
pos_sum = d
neg_sum = 0
elif d < 0:
# We need to decrement
d = -d
if d > neg_sum:
result += d - neg_sum
neg_sum = d
pos_sum = 0
else:
pos_sum = 0
neg_sum = 0
return result