-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
92 lines (83 loc) · 2.5 KB
/
main.cpp
File metadata and controls
92 lines (83 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Source: https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array
// Title: Minimum Number of Increments on Subarrays to Form a Target Array
// Difficulty: Hard
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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 each value by one.
//
// Return the minimum number of operations to form a `target` array from `initial`.
//
// The test cases are generated so that the answer fits in a 32-bit integer.
//
// **Example 1:**
//
// ```
// Input: target = [1,2,3,2,1]
// Output: 3
// Explanation: We need at least 3 operations to form the target array from the initial array.
// [**0,0,0,0,0**] increment 1 from index 0 to 4 (inclusive).
// [1,**1,1,1**,1] increment 1 from index 1 to 3 (inclusive).
// [1,2,**2**,2,1] increment 1 at index 2.
// [1,2,3,2,1] target array is formed.
// ```
//
// **Example 2:**
//
// ```
// Input: target = [3,1,1,2]
// Output: 4
// Explanation: [**0,0,0,0**] -> [1,1,1,**1**] -> [**1**,1,1,2] -> [**2**,1,1,2] -> [3,1,1,2]
// ```
//
// **Example 3:**
//
// ```
// Input: target = [3,1,5,4,2]
// Output: 7
// Explanation: [**0,0,0,0,0**] -> [**1**,1,1,1,1] -> [**2**,1,1,1,1] -> [3,1,**1,1,1**] -> [3,1,**2,2**,2] -> [3,1,**3,3**,2] -> [3,1,**4**,4,2] -> [3,1,5,4,2].
// ```
//
// **Constraints:**
//
// - `1 <= target.length <= 10^5`
// - `1 <= target[i] <= 10^5`
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <stack>
#include <vector>
using namespace std;
// Use monotonic stack
class Solution {
public:
int minNumberOperations(vector<int>& target) {
auto st = stack<int>();
st.push(0);
auto ans = 0;
for (auto num : target) {
ans += max(num - st.top(), 0);
while (num <= st.top()) st.pop();
st.push(num);
}
return ans;
}
};
// Use monotonic stack
//
// We don't really need the stack.
// We only need to compare with the top value
class Solution2 {
public:
int minNumberOperations(vector<int>& target) {
auto st = stack<int>();
st.push(0);
auto ans = 0;
auto prev = 0;
for (auto curr : target) {
ans += max(curr - prev, 0);
prev = curr;
}
return ans;
}
};