Module 10 · Dynamic Programming · Arithmetic Slices

Arithmetic slices II subsequence

Like the longest increasing subsequence, nums[i] looks back at every earlier nums[j]. Here what matters is the difference diff = nums[i] - nums[j]: every arithmetic run ending at j with that difference grows by one when nums[i] joins it.

dp[i] is a map from a difference to how many sequences of two or more numbers end at nums[i] with it. A pair (j, i) adds dp[j][diff] + 1 to dp[i][diff]; only the dp[j][diff] part has three numbers or more, so only it counts towards the answer. slices lists the subsequences counted so far.