-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArithmeticSlices.py
56 lines (41 loc) · 1.42 KB
/
ArithmeticSlices.py
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
'''
Given an integer array nums, return the number of all the arithmetic subsequences of nums.
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.
A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].
The test cases are generated so that the answer fits in 32-bit integer.
Example 1:
Input: nums = [2,4,6,8,10]
Output: 7
Explanation: All arithmetic subsequence slices are:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]
Example 2:
Input: nums = [7,7,7,7,7]
Output: 16
Explanation: Any subsequence of this array is arithmetic.
Constraints:
1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
'''
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
res, n = 0, len(nums)
dp = [defaultdict(int) for _ in range(n)]
for i in range(n):
for j in range(i):
diff = nums[i] - nums[j]
dp[i][diff] += 1 + dp[j][diff]
res += dp[j][diff]
return res
'''
Runtime 614 ms Beats 28.96%
Memory 72 MB Beats 31.49%
'''