-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArithmetic Slices.cpp
More file actions
47 lines (45 loc) · 1.53 KB
/
Arithmetic Slices.cpp
File metadata and controls
47 lines (45 loc) · 1.53 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
class Solution { // USING TABULATION
public:
int numberOfArithmeticSlices(vector<int>& nums) {
int n = nums.size();
vector<int>dp(n+1, 0);
int ans = 0;
for(int i = 2; i < n; i++){
if(nums[i] - nums[i-1] == nums[i-1] - nums[i-2]){
dp[i] = dp[i - 1] + 1;
}else{
dp[i] = 0;
}
}
for(auto&x : dp) ans+=x;
return ans;
}
};// USING RECURSION + MEMO
class Solution {
private:
int countArithmeticSlices(vector<int>& nums, int i, vector<int>& dp) {
// Base case: If 'end' is less than 2, there are not enough elements to form a slice.
if (i < 2) return 0;
if (dp[i] != -1) return dp[i];
// Check if the current triplet forms an arithmetic slice.
if ((nums[i] - nums[i - 1]) == (nums[i - 1] - nums[i - 2])) {
// One valid slice is found ending at 'end'.
// Additionally, any slices ending at 'end - 1' can be extended by the current element.
dp[i] = 1 + countArithmeticSlices(nums, i - 1, dp);
} else {
// If the current triplet does not form an arithmetic slice, no slices end at 'end'.
dp[i] = 0;
}
return dp[i];
}
public:
int numberOfArithmeticSlices(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n, -1);
int totalSlices = 0;
for(int i = 2; i < n; i++){
totalSlices+=countArithmeticSlices(nums, i, dp);
}
return totalSlices;
}
};