Advertisement
1988coder

446. Arithmetic Slices II - Subsequence

Jan 3rd, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. import java.util.HashMap;
  2.  
  3. /**
  4.  * Dynamic Programming
  5.  *
  6.  * Refer:
  7.  * https://leetcode.com/problems/arithmetic-slices-ii-subsequence/solution/
  8.  *
  9.  * DP[i][d] denotes the number of weak arithmetic subsequences that ends with
  10.  * A[i] and its common difference is d.
  11.  *
  12.  * Weak arithmetic subsequences are subsequences that consist of at least two
  13.  * elements and if the difference between any two consecutive elements is the
  14.  * same.
  15.  *
  16.  * Assume we want to append a new element A[i] to existing arithmetic
  17.  * subsequences to form new subsequences. We can append A[i] to an existing
  18.  * arithmetic subsequence, only if the difference between the sequence's last
  19.  * element and A[i] is equal to the sequence's common difference.
  20.  *
  21.  * Thus, we can define the state transitions for the element A[i] intuitively:
  22.  * for all j < i, DP[i][A[i] - A[j]] += DP[j][A[i] - A[j]] + 1.
  23.  *
  24.  * The 1 appears here because we can form a new weak arithmetic subsequence for
  25.  * the pair (i, j).
  26.  *
  27.  * DP[j][A[i] - A[j]] represent the number of subsequences that are not weak.
  28.  *
  29.  * Time Complexity: O(N^2)
  30.  *
  31.  * Space Complexity: O(N^2)
  32.  *
  33.  * N = Length of the input array A.
  34.  */
  35. class Solution {
  36.     public int numberOfArithmeticSlices(int[] A) {
  37.         if (A == null || A.length < 3) {
  38.             return 0;
  39.         }
  40.  
  41.         int result = 0;
  42.         HashMap<Integer, Integer>[] countMap = new HashMap[A.length];
  43.  
  44.         for (int i = 0; i < A.length; i++) {
  45.             countMap[i] = new HashMap<>();
  46.             for (int j = 0; j < i; j++) {
  47.                 // Long is required for overflow. Whenever the difference is beyond the interger
  48.                 // range, its ignored.
  49.                 long delta = (long) A[i] - A[j];
  50.                 if (delta < Integer.MIN_VALUE || delta > Integer.MAX_VALUE) {
  51.                     continue;
  52.                 }
  53.                 int diff = (int) delta;
  54.                 int c1 = countMap[i].getOrDefault(diff, 0);
  55.                 int c2 = countMap[j].getOrDefault(diff, 0);
  56.                 result += c2;
  57.                 countMap[i].put(diff, c1 + c2 + 1);
  58.             }
  59.         }
  60.  
  61.         return result;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement