Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Dynamic Programming
- *
- * validSlicesHere = Number of valid slices ending at the index i
- *
- * totalValidSlices = Total number of valid slices seen till now.
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(1)
- *
- * N = Length of the input array A.
- */
- class Solution {
- public int numberOfArithmeticSlices(int[] A) {
- if (A == null || A.length < 3) {
- return 0;
- }
- int validSlicesHere = 0;
- int validSlicesSoFar = 0;
- for (int i = 2; i < A.length; i++) {
- // long is required to handle inout [Integer.MIN_VALUE, Integer.MAX_VALUE,
- // Integer.MAX_VALUE - 1]
- if ((long) A[i] - A[i - 1] == (long) A[i - 1] - A[i - 2]) {
- validSlicesHere++;
- validSlicesSoFar += validSlicesHere;
- } else {
- validSlicesHere = 0;
- }
- }
- return validSlicesSoFar;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement