Derivative Sequence

243 阅读1分钟

Description

Given a sequence of K elements, we can calculate its difference sequence by taking the difference between each pair of adjacent elements. For instance, the difference sequence of {5,6,3,9,-1} is {6-5,3-6,9-3,-1-9} = {1,-3,6,-10}.

Formally, the difference sequence of the sequence a1, a2, ... , ak is b1, b2, ... , bk-1, where bi = ai+1 - ai.The derivative sequence of order N of a sequence A is the result of iteratively applying the above process N times. For example, if A = {5,6,3,9,-1}, the derivative sequence of order 2 is: {5,6,3,9,-1} -> {1,-3,6,-10} -> {-3-1,6-(-3),-10-6} = {-4,9,-16}.

You will be given a sequence a as a int[] and the order n. Return a int[] representing the derivative sequence of order n of a.

Definition

Class:DerivativeSequence
Method:derSeq
Parameters:int[], int
Returns:int[]
Method signature:int[] derSeq(int[] a, int n)
(be sure your method is public)

Notes

The derivative sequence of order 0 is the original sequence. See example 4 for further clarification.

Constraints

  • a will contain between 1 and 20 elements, inclusive.
  • Each element of a will be between -100 and 100, inclusive.
  • n will be between 0 and K-1, inclusive, where K is the number of elements in a.

Example1

{5,6,3,9,-1}

1

Returns: {1, -3, 6, -10 }

Example2

{5,6,3,9,-1}

2

Returns: {-4, 9, -16}

Example3

{5,6,3,9,-1}

4

Returns: {-38}

Example4

{4,4,4,4,4,4,4,4}

3

{0, 0, 0, 0, 0}

Solution

Computing a sequence of derivatives is a recursion.

1) Finding the basic cases

  • Whether given n is 0, return origin integer array if yes. Otherwise, start recursive

2) Finding the recursive relationship

  • When recursing, the calculated derivative sequence is passed in each time, and n-1
public class DerivativeSequence {
    public static int[] derSeq(int[] a, int n) {
        if (n == 0) {
            return a;
        }
        return derSeq(getSeq(a), n - 1);
    }

    public static int[] getSeq(int[] a) {
        int[] res = new int[a.length - 1];
        for (int i = 0; i < a.length - 1; i++) {
            res[i] = a[i + 1] - a[i];
        }
        return res;
    }
}

Time Complexity

O(n)