We are asked to count the number of arithmetic subarrays (length ≥ 3) inside the array.
Key insights:
- An arithmetic slice means:
nums[i] - nums[i-1] == nums[i-1] - nums[i-2]
- If
nums[i-2..i]forms an arithmetic slice, then extending it by one element may form a longer arithmetic slice. - Use DP to track how many arithmetic slices end at index
i.
- Initialize a DP array
dp[n]with zeros.
dp[i]= number of arithmetic slices ending at indexi.
- For each
ifrom2ton-1:
- If
nums[i] - nums[i-1] == nums[i-1] - nums[i-2], then:dp[i] = dp[i-1] + 1;
- This works because any arithmetic slice ending at
i-1can be extended toi. - Plus, the new slice
[i-2, i-1, i]itself counts as one.
- This works because any arithmetic slice ending at
- The final answer =
sum(dp)(accumulate all contributions).
- DP definition:
dp[i]only depends ondp[i-1]. - Arithmetic extension: once a sequence is arithmetic, adding a new element with the same difference extends it.
- Optimization: we don’t need the whole
dparray — only a running variable.
- Time:
O(n)— single pass through the array. - Space:
O(n)with DP array.- Can be reduced to
O(1)using just one variable.