Minimum Number of Increments on Subarrays to Form a Target Array LeetCode solution in Java

1
// Imagine 3 cases
2
// Case 1. [3,2,1], we need 3 operations.
3
// Case 2. [1,2,3], we need 3 operations.
4
// Case 3. [3,2,1,2,3], we need 5 operations.
5
// What we need to add is actually the diff (cur - prev)
6
// Time complexity: O(N)
7
// Space complexity: O(1)
8
class Solution {
9
public int minNumberOperations(int[] target) {
10
int res = 0;
11
int prev = 0;
12
for (int cur : target) {
13
if (cur > prev) {
14
res += cur - prev;
15
}
16
prev = cur;
17
}
18
return res;
19
}
20
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0