413.Arithmetic Slices
Tags: [sliding_window]
Link: https://leetcode.com/problems/arithmetic-slices/?tab=Description
A sequence of number 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, these are arithmetic sequence:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2, 5, 7
A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.
A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.
The function should return the number of arithmetic slices in the array A.
Example:
A = [1, 2, 3, 4]
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
Solution: sliding_window
class Solution(object):
def numberOfArithmeticSlices(self, A):
"""
:type A: List[int]
:rtype: int
"""
if not A or len(A) < 3:
return 0
a_len = len(A)
counter = 0
start = 0
end = 1
curr_delta = A[end] - A[start]
end += 1
while end < a_len:
curr = A[end]
if curr - A[end - 1] == curr_delta:
end += 1
else:
window_len = (end - 1) - start + 1
if window_len >= 3:
counter += ((window_len - 2) + 1) * (window_len - 2) / 2
start = end - 1
curr_delta = A[end] - A[start]
window_len = (end - 1) - start + 1
if window_len >= 3:
counter += ((window_len - 2) + 1) * (window_len - 2) / 2
return counter
Revelation:
- When we meet the problem about the sequence, we can first think using multiple loops to solve the problem, then we should think whether we can use sliding_window to optimize the solution, finally, we may think whether we can use DP.
- If the max length of the arithmetic sequence is max_len, the max number of arithmetic sequences should be max_num = (max_len - 2) + (max_len - 2 - 1) + (max_len - 2 - 2) + (max_len - 2 - 3) + ... + 1 = k + (k - 1) + (k - 2) + (k - 3) + ... + 1 = (1 + k) * k / 2 = (首项 + 末项) * 项数 / 2
Note:
- Time complexity = O(n), n is the number of elements in the given array.