Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created October 30, 2025 22:25
Show Gist options
  • Select an option

  • Save Ifihan/101a8d767b20d6992947697a6b86d3dd to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/101a8d767b20d6992947697a6b86d3dd to your computer and use it in GitHub Desktop.
Minimum Number of Increments on Subarrays to Form a Target Array

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment