commit 318857f0b9cb76b323227784a6d6483a3b2f01cb
parent 4d2f275db2683af3d8f8d82af5d5b8d2ecb805d3
Author: Jack Sangdahl <jack@pngu.org>
Date: Wed, 29 Oct 2025 22:24:49 -0600
1526. minimum number of increments on subarrays to form a target array
Diffstat:
2 files changed, 59 insertions(+), 0 deletions(-)
diff --git a/min_num_incr_subarr_target.c b/min_num_incr_subarr_target.c
@@ -0,0 +1,28 @@
+// 1526. Minimum Number of Increments on Subarrays to Form a Target Array
+#include "leetcode.h"
+
+/*
+ * you are given an integer array 'target'. you have an integer array 'initial'
+ * of the same size as 'target' with all elements initially zeros. in one
+ * operation, you can choose any subarray from 'initial' and increment ach value
+ * by one. return the minimum number of operations to form a 'target' array from
+ * 'initial'. the test cases are generated such that the answer will fit in a
+ * 32-bit integer.
+ */
+
+int minNumberOperations(int *target, int targetSize) {
+ int ans = 0, prev = 0;
+ for (int i = 0; i < targetSize; i++) {
+ if (target[i] > prev)
+ ans += target[i] - prev;
+ prev = target[i];
+ }
+ return ans;
+}
+
+int main() {
+ int t1[] = {1, 2, 3, 2, 1}, t2[] = {3, 1, 1, 2}, t3[] = {3, 1, 5, 4, 2};
+ printf("%d\n", minNumberOperations(t1, ARRAY_SIZE(t1))); // expect: 3
+ printf("%d\n", minNumberOperations(t2, ARRAY_SIZE(t2))); // expect: 4
+ printf("%d\n", minNumberOperations(t3, ARRAY_SIZE(t3))); // expect: 7
+}
diff --git a/min_num_incr_subarr_target.py b/min_num_incr_subarr_target.py
@@ -0,0 +1,31 @@
+# 1526. Minimum Number of Increments on Subarrays to Form a Target Array
+
+"""
+you are given an integer array 'target'. you have an integer array 'initial'
+of the same size as 'target' with all elements initially zeros. in one
+operation, you can choose any subarray from 'initial' and increment ach value
+by one. return the minimum number of operations to form a 'target' array from
+'initial'. the test cases are generated such that the answer will fit in a
+32-bit integer.
+"""
+
+
+class Solution(object):
+ def minNumberOperations(self, target):
+ """
+ :type target: List[int]
+ :rtype: int
+ """
+ ans, prev = 0, 0
+ for i in target:
+ if i > prev:
+ ans += i - prev
+ prev = i
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minNumberOperations(target=[1, 2, 3, 2, 1]))
+ print(obj.minNumberOperations(target=[3, 1, 1, 2]))
+ print(obj.minNumberOperations(target=[3, 1, 5, 4, 2]))