-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Patching Array.cpp
56 lines (49 loc) · 1.5 KB
/
Patching Array.cpp
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
/* Scroll below to see JAVA code also */
/*
MY YOUTUBE VIDEO ON THIS Qn : https://www.youtube.com/watch?v=K2IomuIFbPg
Company Tags : GOOGLE
Leetcode Link : https://leetcode.com/problems/patching-array/description/
*/
/************************************************** C++ **************************************************/
//Approach (Greedy observation)
//T.C : O(max(l, log(n)), l = length of nums
//S.C : O(1)
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
long maxReach = 0;
int patch = 0;
int i = 0;
while(maxReach < n) {
if(i < nums.size() && nums[i] <= maxReach+1) {
maxReach += nums[i];
i++;
} else {
maxReach += (maxReach + 1);
patch++;
}
}
return patch;
}
};
/************************************************** JAVA **************************************************/
//Approach (Greedy observation)
//T.C : O(max(l, log(n)), l = length of nums
//S.C : O(1)
class Solution {
public int minPatches(int[] nums, int n) {
long maxReach = 0;
int patch = 0;
int i = 0;
while (maxReach < n) {
if (i < nums.length && nums[i] <= maxReach + 1) {
maxReach += nums[i];
i++;
} else {
maxReach += (maxReach + 1);
patch++;
}
}
return patch;
}
}