Skip to content

Commit 3f2ef6e

Browse files
committed
Arithmetic Slices
1 parent de6efba commit 3f2ef6e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

413-arithmetic-slices.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/arithmetic-slices/
3+
4+
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
5+
For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
6+
Given an integer array nums, return the number of arithmetic subarrays of nums.
7+
A subarray is a contiguous subsequence of the array.
8+
9+
Example 1:
10+
Input: nums = [1,2,3,4]
11+
Output: 3
12+
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
13+
14+
Example 2:
15+
Input: nums = [1]
16+
Output: 0
17+
18+
Constraints:
19+
1 <= nums.length <= 5000
20+
-1000 <= nums[i] <= 1000
21+
"""
22+
class Solution:
23+
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
24+
if len(nums) < 3:
25+
return 0
26+
27+
diff = float('inf')
28+
ap_arrays = cur_length = 0
29+
30+
for index in range(1, len(nums)):
31+
if nums[index] - nums[index-1] == diff:
32+
cur_length += 1
33+
else:
34+
diff = nums[index] - nums[index-1]
35+
cur_length = 2
36+
37+
if cur_length >= 2:
38+
ap_arrays += (cur_length - 2)
39+
40+
return ap_arrays

0 commit comments

Comments
 (0)