Java Dailly Tip: Codility Solitaire Number Solution

Java Dailly Tip: Codility Solitaire Number Solution

Problem

Recently, I solved the following task from Codility https://app.codility.com/programmers/lessons/17-dynamic_programming/number_solitaire/. How to solve them quickly and efficiently in Java?

Solution

The quickest solution to this problem that comes to mind in Java that comes to mind is:

public class NumberSolitaireSolution {
    public static void main(String[] args) {
        System.out.println(new NumberSolitaireSolution().solution(new int[]{1, -2, 0, 9, -1, -2}));
    }

    private int solution(int[] intsArray) {
        int intArrayLength = intsArray.length;
        int[] newIntArray = new int[intArrayLength];
        newIntArray[0] = intsArray[0];

        for (int firstIndex = 1; firstIndex < intArrayLength; firstIndex++) {
            double negativeInfinity = Double.NEGATIVE_INFINITY;
            for (int secondIndex = 1; secondIndex <= 6; secondIndex++) {
                if (firstIndex - secondIndex < 0) {
                    break;
                }
                double solution = newIntArray[firstIndex - secondIndex] + intsArray[firstIndex];
                negativeInfinity = Double.max(solution, negativeInfinity);
            }
            newIntArray[firstIndex] = (int) negativeInfinity;
        }

        return newIntArray[intArrayLength-1];
    }
}

Share this Post