The problem is to calculate the number of arithmetic slices in a given list of integers.
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.
Given an array of integers nums
, return the number of arithmetic subarrays of nums
.
Example 1:
Input: nums = [1, 2, 3, 4]
Output: 3
Explanation: There are three arithmetic slices in input array: [1, 2, 3], [2, 3, 4], and [1, 2, 3, 4] itself.
Example 2:
Input: nums = [1]
Output: 0
current
to keep track of the number of arithmetic slices ending at the current position and a variable total
to keep the total count of arithmetic slices.current
count and add it to the total
.current
count to zero.def numberOfArithmeticSlices(nums):
if len(nums) < 3:
return 0
total, current = 0, 0
for i in range(2, len(nums)):
if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
current += 1
total += current
else:
current = 0
return total
This solution is efficient and meets the problem’s requirements by iterating over the list in linear time and using constant space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?