기본 콘텐츠로 건너뛰기

코딩 테스트 - MaxProfit

Maximum slice problem 으로 넘어왔습니다!
재미있...는...? codility의 영어공부...★ 

문제에 주식 얘기가 나와서 너무나 멜랑콜리해집니다.
저의 삼성 주식은 고등어가 되었고,
LG 주식은 갈치가 되었기 때문이지오... ↓ 하하




package codility;

import java.util.Arrays;

public class MaxProfit_221230 {
    public static void main(String[] args) {
        int [] A = {23171, 21011, 21123, 21366, 21013, 21367};
        System.out.println(solution(A));
    }

    public static int solution(int[] A) {
        if(A.length == 1 || A.length == 0){
            //0~1은 이익이 없으니 끝냄
            return 0;
        }

        int answer = 0;  
        int min = Arrays.stream(A).min().getAsInt();
        int flag = 0;
       
        for(int i = 0; i < A.length; i++){
            if(A[i] == min){
                if(i == A.length-1){
                    //마지막이니 종료
                    return 0;
                }else{
                    flag = i;
                    break;            
                }
            }
        }

       
        int [] arr = Arrays.copyOfRange(A, flag, A.length);
        int max = Arrays.stream(arr).max().getAsInt();


        answer = max - min;
       

        return answer;
    }
}


정확성을 개선해봅니다.
Arrays를 버리고 초심으로 돌아가 for문을 돌려봅니다.

package codility;

public class MaxProfit_221230 {
    public static void main(String[] args) {
        int [] A = {23171, 21011, 21123, 21366, 21013, 21367};
        System.out.println(solution(A));
    }

    public static int solution(int[] A) {
         
        int answer = 0;

        int temp = 0;
        int min = 400000;
        int max = 0;        
       
        for(int i = 0; i < A.length; i++){            
           
            if(A[i] < min){
                min = A[i];
                max = A[i];
            }else if(A[i] > max){
                max = A[i];
            }
       
            temp = max - min;
           
            if(temp > answer){
                //마이너스 값 체크용
                answer = temp;
            }
        }
        return answer;
    }
}


temp를 굳이 둬서 마이너스 값 나오는 것을 막아줍니다.




댓글