Skip to content

Commit 10ee553

Browse files
committed
Solution as on 03-03-2022 05:52 pm
1 parent d940de5 commit 10ee553

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

0413. Arithmetic Slices.cpp

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
class Solution
2+
{
3+
public:
4+
int numberOfArithmeticSlices(vector<int> &nums)
5+
{
6+
// if nums size is less than 3 return false
7+
if (nums.size() < 3)
8+
return 0;
9+
10+
int cnt = 0, diff;
11+
12+
for (int i = 0; i < nums.size() - 2; ++i)
13+
{
14+
// storing diff of first 2 elements
15+
diff = nums[i + 1] - nums[i];
16+
17+
// checking for consecutive elements with same difference.
18+
for (int j = i + 2; j < nums.size(); ++j)
19+
{
20+
// if we find the same diff of next 2 elements
21+
// this means we find consecutive elements
22+
// increase the Count
23+
if (nums[j] - nums[j - 1] == diff)
24+
++cnt;
25+
else
26+
// break as we need to cnt for consecutive diff elements
27+
break;
28+
}
29+
}
30+
// return cnt
31+
return cnt;
32+
}
33+
};
34+
35+
class Solution
36+
{
37+
public:
38+
int numberOfArithmeticSlices(vector<int> &nums)
39+
{
40+
if (nums.size() < 3)
41+
return 0;
42+
43+
int cnt = 0, diff = 0, ind = 0;
44+
int prev_diff = nums[1] - nums[0];
45+
46+
for (int i = 1; i < nums.size() - 1; ++i)
47+
{
48+
// curr difference
49+
int diff = nums[i + 1] - nums[i];
50+
51+
// if we find same diff of consecutive elements
52+
// increase count
53+
if (diff == prev_diff)
54+
++ind;
55+
56+
else
57+
{
58+
// update prev diff with curr diff
59+
// as we don't find consecutive elements with same diff
60+
prev_diff = diff;
61+
ind = 0; // make ind to 0
62+
}
63+
64+
// add cosecutive arithmetic sequence cnt
65+
cnt += ind;
66+
}
67+
68+
return cnt;
69+
}
70+
};

0 commit comments

Comments
 (0)