Java Concise Solution


  • 1
    C

    Keep track of previous difference and calculate current slice number.
    This is definitely an easy problem instead of a medium one.

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

  • 0
    M

    This is really an interesting solution. I really like your approach.


Log in to reply
 

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