forked from srinidh-007/Coding_Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharithematic-slices.py
More file actions
49 lines (40 loc) · 1.16 KB
/
arithematic-slices.py
File metadata and controls
49 lines (40 loc) · 1.16 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
# 413 ARITHEMATIC SLICES
# https://leetcode.com/problems/arithmetic-slices/
# My Approach:
# As I traverse the list, find the lengths of the subarrays which follows the rule c-b == b-a for [...,a,b,c...].
# And calculate the number of possible combinations thematically. Then continue the same.
def numberOfArithmeticSlices(nums):
if len(nums) < 3:
return 0
res, ln = 0, 0
for index in range(2, len(nums)):
if nums[index] - nums[index - 1] == nums[index - 1] - nums[index - 2]:
ln += 3 if ln == 0 else 1
else:
# For len=6, combinations =
# ((6-3)+1) + ((6-4)+1) + ((6-5)+1) + (( 6-6)+1)
total = 0
for i in range(3, ln + 1):
total += ln - i + 1
res += total
ln = 0
total = 0
for i in range(3, ln + 1):
total += ln - i + 1
res += total
return res
nums = [1,2,3,4]
ans = numberOfArithmeticSlices(nums)
print(ans)
#
# Example
# 1:
#
# Input: nums = [1, 2, 3, 4]
# Output: 3
# Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
# Example
# 2:
#
# Input: nums = [1]
# Output: 0