본문 바로가기
프로그래밍/알고리즘 연습

[TopCoder,전체 탐색]암호

by mrvan 2019. 2. 10.

1. 내가 짠 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class test {
    public static void main(String[] args){
        test test = new test();
        int[] number = {1,3,2,1,1,3};
//        int[] number = {1,2,3};
        long answer = test.encrypt(number);
        System.out.println(answer);
    }
    public long encrypt(int[] numbers){
        int temp;
        long ans=0;
        long mul;
        for(int i =0 ;i< numbers.length;i++){
            mul=1;
            temp = numbers[i];
            numbers[i]++;
            for(int j=0;j< numbers.length;j++){
                mul = mul * numbers[j];
            }
            ans = Math.max(ans,mul);
            numbers[i]=temp;
        }
        return ans;
    }
 
}
 
--------------------------결과-----------------------------------
36
cs


2. 개선 코드

 - 해당 문제는 가장 작은 숫자에 +1을 하면된다

-> 숫자(n)에 +1을 하게 되면 곱의 증가율은 (n+1)/n이 되므로, 가장 작은 n을 찾으면 된다.

 - 따라서 정렬을 사용하여 가장 작은 숫자를 찾는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.Arrays;
 
public class test {
    public static void main(String[] args){
        test test = new test();
        int[] number = {1,3,2,1,1,3};
//        int[] number = {1,2,3};
        long answer = test.encrypt(number);
        System.out.println(answer);
    }
    public long encrypt(int[] numbers){
        long mul=1;
        Arrays.sort(numbers);
        numbers[0]++;
        for(int j=0;j< numbers.length;j++){
            mul = mul * numbers[j];
        }
        return mul;
    }
 
}
 
 
--------------------------결과-----------------------------------
36
cs