Concise JAVA DP solution


  • 0
    S
    public class Solution {
        public int numberOfArithmeticSlices(int[] A) {
            if (A == null || A.length < 3) {
                return 0;
            }
            int[] dp = new int[A.length];
            int[] index = new int[A.length];
            int res = 0;
            for (int i = 2; i < A.length; i++) {
                if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
                    if (dp[i - 1] == 0) {
                        dp[i] = 1;
                        index[i] = 3;
                    } else {
                        dp[i] = dp[i - 1] + index[i - 1] - 1;
                        index[i] = index[i - 1] + 1;
                    }
                } else {
                    res += dp[i - 1];
                }
            }
            return res + dp[dp.length - 1];
        }
    }
    

Log in to reply
 

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