LeetCode Solutions

413. Arithmetic Slices

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  int numberOfArithmeticSlices(vector<int>& A) {
    const int n = A.size();
    if (n < 3)
      return 0;

    vector<int> dp(n);  // # arithmetic slices ends at i

    for (int i = 2; i < A.size(); ++i)
      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
        dp[i] = dp[i - 1] + 1;

    return accumulate(begin(dp), end(dp), 0);
  }
};
			

class Solution {
  public int numberOfArithmeticSlices(int[] A) {
    final int n = A.length;
    if (n < 3)
      return 0;

    int[] dp = new int[n]; // dp[i] := # of arithmetic slices ends at A[i]

    for (int i = 2; i < n; ++i)
      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
        dp[i] += dp[i - 1] + 1;

    return Arrays.stream(dp).sum();
  }
}
			

class Solution {
 public:
  int numberOfArithmeticSlices(vector<int>& A) {
    int ans = 0;
    int dp = 0;  // # arithmetic slices ends at i

    for (int i = 2; i < A.size(); ++i)
      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
        ans += ++dp;
      else
        dp = 0;

    return ans;
  }
};