[GO] [100%] MaxProductOfThree (src & jUnit)

Painless

MaxProductOfThree

Maximize A [P] * A [Q] * A [R] for any triplet (P, Q, R). image.png

Task description

Given a non-empty array A consisting of N integers. The product of triplets (P, Q, R) is equal to A [P] * A [Q] * A [R](0 ≤ P <Q <R <N).

For example, the following array A:

Example


   A [0] = -3
   A [1] = 1
   A [2] = 2
   A [3] = -2
   A [4] = 5
   A [5] = 6

The following triplet example is included.

Your goal is to find the maximum product of triplets.

Write a function:

class solution {public int solution(int [] A); }

Given a non-empty array A, returns the value of the maximum product of any triplet.

For example, given the following array A:

Example


   A [0] = -3
   A [1] = 1
   A [2] = 2
   A [3] = -2
   A [4] = 5
   A [5] = 6

The function must return 60 because the product of triplets (2, 4, 5) is the largest.

Write a ** efficient ** algorithm for the following assumptions:


solve

image.png

Program MaxProductOfThreeSolution.java

    public int solution(int[] A) {
        int max1 = -9999;
        int max2 = -9999;
        int max3 = -9999;
        int min2 = 9999;
        int min1 = 9999;

        for (int a : A) {
            if (a > max1) {
                max3 = max2;
                max2 = max1;
                max1 = a;
            } else if (a > max2) {
                max3 = max2;
                max2 = a;
            } else if (a > max3) {
                max3 = a;
            }

            if (a < min1) {
                min2 = min1;
                min1 = a;
            } else if (a < min2) {
                min2 = a;
            }
        }

        int maxProduct = max1 * max2 * max3;

        if (max1 <= 0 || min1 >= 0) {
            //All negative||All positive
            return maxProduct;
        } else {
            if (min2 < 0 ) {
                //At least two negatives
                int temp = max1 * min1 * min2;
                if (temp > maxProduct) return temp;
            }
        }

        return maxProduct;
    }

Detected time complexity:

O(N * log(N))

jUnit MaxProductOfThreeSolutionTest.java

Report trainingUP9UFH-H2Y


Recommended Posts

[100%] MaxProductOfThree (src & jUnit)
[100%] CyclicRotation (src & jUnit)
[100%] FrogJmp (src & jUnit)
[100%] FrogRiverOne (src & jUnit)
[100%] OddOccurrencesInArray (src & jUnit)
[100%] MinAvgTwoSlice (src & junit)
[100%] PassingCars (src & junit)
[100%] PermCheck (src & junit)
[100%] TapeEquilibrium (src & jUnit)
[100%] BinaryGap (src & jUnit)
[100%] [GenomicRangeQuery] (src & junit & author's note)
[100%] MaxCounters (src & junit & author's note)
[100%] Distinct (src & junit & author's note)
[100%] CountDiv (src & junit & author's note)
JUnit 4 notes
JUnit memorandum