본문 바로가기

공부하자/Codility

[Codility] Lesson9. MaxProfit (C#)

문제: app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/

 

MaxProfit coding task - Learn to Code - Codility

Given a log of stock prices compute the maximum possible earning.

app.codility.com

 

 

 

            if (A.Length <= 1)
                return 0;
            int maxProfit = 0;
            int nowProfit = 0;
            int minValue = A[0];
            for (int i = 1; i < A.Length; i++)
            {
                nowProfit = A[i] - minValue;
                if (maxProfit < nowProfit)
                {
                    maxProfit = nowProfit;
                }
                if (minValue > A[i])
                    minValue = A[i];
            }
            if (maxProfit < 0)
                return 0;

            return maxProfit;