Advertisement
1988coder

413. Arithmetic Slices

Jan 3rd, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. /**
  2.  * Dynamic Programming
  3.  *
  4.  * validSlicesHere = Number of valid slices ending at the index i
  5.  *
  6.  * totalValidSlices = Total number of valid slices seen till now.
  7.  *
  8.  * Time Complexity: O(N)
  9.  *
  10.  * Space Complexity: O(1)
  11.  *
  12.  * N = Length of the input array A.
  13.  */
  14. class Solution {
  15.     public int numberOfArithmeticSlices(int[] A) {
  16.         if (A == null || A.length < 3) {
  17.             return 0;
  18.         }
  19.  
  20.         int validSlicesHere = 0;
  21.         int validSlicesSoFar = 0;
  22.  
  23.         for (int i = 2; i < A.length; i++) {
  24.             // long is required to handle inout [Integer.MIN_VALUE, Integer.MAX_VALUE,
  25.             // Integer.MAX_VALUE - 1]
  26.             if ((long) A[i] - A[i - 1] == (long) A[i - 1] - A[i - 2]) {
  27.                 validSlicesHere++;
  28.                 validSlicesSoFar += validSlicesHere;
  29.             } else {
  30.                 validSlicesHere = 0;
  31.             }
  32.         }
  33.  
  34.         return validSlicesSoFar;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement