increasing code performance of codility

Basic math:

X + nD >= Y
nD >= Y - X
n >= (Y - X) / D

The minimum value for n will be the result of rounding up the division of (Y - X) by D.

Big O analysis for this operation:

  • Complexity: O(1). It's a difference, a division and a round up
  • Worst-case space complexity is O(1): you can have at most 3 more variables:
    • Difference for Y - X, let's assign this into Z.
    • Division between Z by D, let's assign this into E.
    • Rounding E up, let's assign this into R (from result).

Java(One Line), Correctness 100%, Performance 100%, Task score 100%

// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int X, int Y, int D) {
      return (int) Math.ceil((double) (Y - X) / (double) D);
    }
}

Tags:

Java