My approach is to track how many times the array increases. I start by setting the number of operations to the first element since that’s how many increments are needed to reach it from zero. Then, as I move through the array, I only add the positive differences between consecutive elements—because whenever a value increases compared to the previous one, that increase represents new operations needed. This gives the minimum number of operations efficiently in one pass.
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
operations = target[0]
for i in range(1, len(target)):
if target[i] > target[i - 1]:
operations += target[i] - target[i - 1]
return operations- Time: O(n)
- Space: O(1)