-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_413_ArithmeticSlices.cpp
68 lines (48 loc) · 1.39 KB
/
LC_413_ArithmeticSlices.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
57
58
59
60
61
62
63
64
65
66
67
68
/*
https://leetcode.com/problems/arithmetic-slices/
413. Arithmetic Slices
*/
class Solution {
public:
int numberOfArithmeticSlices1(vector<int>& nums) {
int n = nums.size();
if(n>=0 && n<=2) return 0;
vector<int> dp(n,0); // dp[i] arithmetic slices of length 3 ending at index i
int total =0;
for(int i=2; i<nums.size(); i++)
{
if((nums[i]-nums[i-1])==(nums[i-1]-nums[i-2]))
{
dp[i] = dp[i-1]+1;
total+=dp[i];
}
}
return total;
}//end
int numberOfArithmeticSlices(vector<int>& nums) {
int n = nums.size();
if(n>=0 && n<=2) return 0;
int slow=0, fast= 1;
int diff=0;
int total =0;
diff = nums[fast]-nums[slow];
fast++ ; // fast ==>2
for( ;fast < nums.size(); fast++)
{
if(nums[fast]-nums[fast-1] == diff)
{
if(fast-slow+1>=3)
{
total+=fast-slow+1-2;
}
continue;
}
else
{
slow = fast-1;
diff = nums[fast]-nums[slow];
}
}
return total;
}//end
};