340/670

340. Arithmetic Slices

Medium

A run of numbers is arithmetic when it has at least 3 elements and every gap between neighbors is the same. So [1, 3, 5, 7] qualifies (gap 2 everywhere), [9, 6, 3] qualifies (gap −3), but [1, 2, 4] does not.

Given an integer array nums, count how many contiguous subarrays of nums are arithmetic. Subarrays at different positions count separately even if their values repeat, and the whole array may itself be one of them.

Return that count as a single integer.

Example 1:

Input: nums = [1, 2, 3, 4]

Output: 3

Explanation: The arithmetic subarrays are [1, 2, 3], [2, 3, 4], and [1, 2, 3, 4] itself — three in total.

Example 2:

Input: nums = [1, 2, 3, 4, 8, 9, 10]

Output: 4

Explanation: The gap breaks between 4 and 8, so the slices are [1, 2, 3], [2, 3, 4], [1, 2, 3, 4], and [8, 9, 10].

Example 3:

Input: nums = [1]

Output: 0

Explanation: An arithmetic slice needs at least 3 elements, so a single element yields none.

Constraints:

  • 1 ≤ nums.length ≤ 5000
  • -1000 ≤ nums[i] ≤ 1000

Hints:

The array of consecutive differences d[i] = nums[i] − nums[i−1] tells the whole story: a subarray is arithmetic exactly when the differences inside it are all equal.

Count slices by where they END. If dp is the number of arithmetic slices ending at index i−1, and the difference at i matches the one at i−1, then every one of those slices extends — plus one brand-new slice of length 3. So dp becomes dp + 1; on a mismatch it resets to 0. Sum dp over the scan.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [1, 2, 3, 4]

Expected output: 3