Day94

강태훈·2026년 5월 15일

nbcamp TIL

목록 보기
94/97

알고리즘 코드카타

Product Price at a Given Date

with rn_product as (
    select product_id, new_price, ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY change_date desc ) AS rn
    from Products
    where change_date <= '2019-08-16'
), group_product as (
    select product_id
    from Products
    group by product_id
)

select a.product_id, ifnull(b.new_price, 10) as price
from group_product a
left join rn_product b
on a.product_id = b.product_id
where b.rn = 1 or b.rn is null;

N개의 최소공배수

import java.util.Arrays;

class Solution {
    public int solution(int[] arr) {
        int answer = 0;

        int[] array = arr;

        for (int i = 0; i < halflength(arr.length); i++) {
            if (array.length <= 1){
                break;
            }
            array = arrays(array);
        }
        System.out.println(Arrays.toString(array));
        answer = array[0];
        for (int j : arr) {
            answer *= (j / array[0]);
        }

        return answer;
    }
    public int halflength(int l){
        if (l%2 != 0){
            return l/2 + 1;
        }
        return l/2;
    }

    public int[] arrays(int[] list){
        int[] array = new int[halflength(list.length)];

        boolean odd = false;
        if (list.length % 2 != 0){
            odd = true;
        }

        for (int i = 0; i < halflength(list.length); i++) {
            if(odd && i == halflength(list.length)-1){
                array[i] = list[list.length-1];
            }else {
                array[i] = gcd(list[2*i], list[2*i+1]);
            }
        }

        return array;
    }

    // 최대공약수 찾기
    public int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return a;
    }
}
  • 길어졌으나 실패..너무 복잡하게 생각했음을 깨달았다
class Solution {
    public int solution(int[] arr) {
        int answer = arr[0];

        for (int i = 1; i < arr.length; i++) {
            answer = lcm(answer, arr[i]);
        }

        return answer;
    }

    //최소공배수 찾기
    public int lcm(int a, int b) {
        return (a / gcd(a, b)) * b;
    }

    // 최대공약수 찾기
    public int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return a;
    }
}

0개의 댓글