LeetCode Challenge Day 45 β 1526. Minimum Number of Increments on Subarrays to Form a Target Array
Nitin Ahirwal / October 30, 2025
Hey folks
This is Day 45 of my LeetCode streak π.
Todayβs problem is 1526. Minimum Number of Increments on Subarrays to Form a Target Array β a hard greedy problem that looks tricky at first but simplifies once you spot the pattern.
π Problem Statement
You are given an integer array target.
You start with another array initial of the same size filled with zeros.
In one operation, you can choose a subarray of initial and increment each value in that subarray by 1.
Return the minimum number of operations required to form target.
Example 1:
Input: target = [1,2,3,2,1]
Output: 3
Example 2:
Input: target = [3,1,1,2]
Output: 4
Example 3:
Input: target = [3,1,5,4,2]
Output: 7
π‘ Intuition
Instead of simulating each subarray increment, notice this:
- If
target[i] > target[i-1], we need(target[i] - target[i-1])new operations. - If
target[i] <= target[i-1], no new operations are needed. - For the very first element
target[0], we need exactlytarget[0]operations.
Thus, the answer is simply the sum of all positive increases between consecutive elements.
π Approach
- Initialize
ops = target[0]. - Iterate from index
1ton-1.- If
target[i] > target[i-1], add the difference toops.
- If
- Return
opsas the result.
β±οΈ Complexity Analysis
-
Time complexity:
(O(n)) β one linear pass. -
Space complexity:
(O(1)) β constant space.
π§βπ» Code (JavaScript)
/**
* @param {number[]} target
* @return {number}
*/
var minNumberOperations = function(target) {
let ops = target[0]; // base cost for first element
for (let i = 1; i < target.length; i++) {
if (target[i] > target[i - 1]) {
ops += target[i] - target[i - 1];
}
}
return ops;
};
π§ͺ Example Walkthrough
Input: target = [3,1,5,4,2]
-
Start: ops = 3
-
Compare 1 vs 3 β no increase
-
Compare 5 vs 1 β +4 β ops = 7
-
Compare 4 vs 5 β no increase
-
Compare 2 vs 4 β no increase
β Output = 7
π₯ Reflections
This problem looked intimidating at first because of the "subarray increment" definition. But once you reframe it as "count the rises," it becomes much simpler and elegant.
Thatβs it for Day 45 of my LeetCode journey!
Onwards to Day 46 π₯
Happy Coding π¨βπ»