Java DP solutuon, O(n) time, O(1) space


  • 0
    L
    public class Solution {
        public int numberOfArithmeticSlices(int[] A) {
            if (A == null || A.length < 3) {
                return 0;
            }
            
            int result = 0;
            int n = A.length;
            int last = 0;
            
            for (int i = 2; i < n; i++) {
                if ((A[i] - A[i - 1]) == (A[i - 1] - A[i - 2])) {
                    last = last + 1;
                } else {
                    last = 0;
                }
                
                result += last;
            }
            
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.