본문 바로가기

공부하자/Codility

[Codility] Lesson6. MaxProductOfThree (C#)

문제: app.codility.com/programmers/lessons/6-sorting/max_product_of_three/

 

MaxProductOfThree coding task - Learn to Code - Codility

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

app.codility.com

 

 

            List<int> ListA = new List<int>(A);
            ListA.Sort();

            if (ListA[A.Length - 1] < 0)
                return ListA[A.Length - 1] * ListA[A.Length - 2] * ListA[A.Length - 3];

            int pre = ListA[0] * ListA[1];
            int post = ListA[A.Length - 2] * ListA[A.Length - 3];
            int result = 0;

            if (pre < post)
                result = post * ListA[A.Length - 1];
            else
                result = pre * ListA[A.Length - 1];

            return result;