스터디사이트 : https://www.hackerrank.com



JAVA Basic : 두 수의 차의 절대값 범위 중 최대값 구하기



※ 조건


변수

a, b : 입력받는 두 수

elements : 두 수 차의 절대값을 구하는 데 필요한 인수. int배열타입으로 저장.

maximumDifference : 두 수 차의 절대값 중 최대값을 저장.

The absolute difference between two integers, a and b, is written as |a-b|. The maximum absolute difference between two integers in a set of positive integers, elements, is the largest absolute difference between any two integers in elements.


The Difference class is started for you in the editor. It has a private integer array (elements) for storing N non-negative integers, and a public integer (maximumDifference) for storing the maximum absolute difference.


Difference 클래스

- 생성자는 파라미터로써 int배열을 가져오며, 이 배열을 elements 인스턴스 변수로써 저장

- maximumDifference는 해당 클래스의 지역변수.


computeDifference() 메소드

 N자리 안에서 두 숫자 사이의 차의 절대값의 최대값을 찾는다

 상기와 같이 찾은 값을 maximumDifference 인스턴스 변수에다가 저장한다.



※ 주어진 코드

: 아래 표시된 영역 안에서만 코딩 할 것.

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
class Difference {
      private int[] elements;
      public int maximumDifference;
 
    // Add your code here
    /* 이곳에 코딩 */
 
// End of Difference class
 
public class Solution {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        sc.close();
 
        Difference difference = new Difference(a);
 
        difference.computeDifference();
 
        System.out.print(difference.maximumDifference);
    }
}
cs


입력

3

1 2 5


출력

4



디버깅1

최대값을 구하는 로직은

우선 초항을 무조건 최대값으로 두고, 그 다음 항이 현 최대값보다 크면 그 값이 최대값으로 대체되는 것으로 해야 할 것이다.


① elements[i] 와 elements[i+1]

혹은

② elements[i-1]와 elements[i] 

의 차를 절대값을 씌워서 구하고 최대값과 비교하는 것이다.

①과 ② 중 어떤 것을 써야 할 것인가!


문제는 for문 돌리는 것이 관건.

초항이 0이고 1항과 2항의 차를 구하는 것이므로, 만약에 i가 0부터 i+1까지라면 i+1은 배열의 최대값보다 커지므로 IndexOutofBoundsException이 나올 것이다.. 


그래서

i를 1부터 배열의 최대값까지만 반복시키기로 한다.

그리고 for문의 내용에는 ②를 채택하여 사용하기로 했다.




코딩연습 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Difference {
      private int[] elements;
      public int maximumDifference;
 
      Difference(int[] elements){
          this.elements = elements;
      } //end constructor
      
      void computeDifference(){
          this.maximumDifference=elements[0];
          int difference;
          System.out.println("maximumDifference (before.for) : " + maximumDifference);
          for(int i=1; i<elements.length; i++){
              difference = Math.abs(elements[i-1- elements[i]);
              System.out.printf("difference[cycle %d] : %d\n", i , difference);
              if(difference > maximumDifference){
                  this.maximumDifference = difference;
              }
              System.out.println("maximumDifference (for) : " + maximumDifference);
          } //end for i
          System.out.println("maximumDifference (exit.for) : " + maximumDifference);
      } //end computeDifference()
// End of Difference class
cs

결과 : 

maximumDifference (before.for) : 1

difference[cycle 1] : 1

maximumDifference (for) : 1

difference[cycle 2] : 3

maximumDifference (for) : 3

maximumDifference (exit.for) : 3

3


디버깅2

elements[] 배열에는 현재 {1, 2, 5} 가 들어가 있고,

|1 - 2| , |1 - 5| , |2 - 1| , |2 - 5| 의 케이스가 있다.

위의 코드는 버블정렬처럼 코딩을 해놨는데, 틀렸다.


그래서 아래와 같은 규칙을 새로 정했다..

Cycle 1 : 1번째 자리를 고정해 놓고, 2번째부터 마지막자리까지 비교를 한다.

Cycle 2 : 2번째 자리를 고정해 놓고, 1번째부터 마지막자리까지 비교를 한다.

Cycle n : n번째 자리를 고정해 놓고, 1번째부터 마지막자리까지 비교를 한다.

단, 고정된 자리와 비교할 자리가 같을 경우는 제외하고, 기존 사이클에서 사용된 자릿수는 제외한다.


 elements.length

k (0, elements.length, 1)

i (k+1, elements.length, 1)

 3

 0

 0 1 2

 1 1 2
 2 



코딩연습 2

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
class Difference {
      private int[] elements;
      public int maximumDifference;
 
      Difference(int[] elements){
          this.elements = elements;
      } //end constructor
      
      void computeDifference(){
          this.maximumDifference=0;
          int difference;
          System.out.println("maximumDifference (before.for) : " + maximumDifference);
          System.out.println("---------------------elements.length : " + elements.length);
          for(int k=0; k<elements.length; k++){
              for(int i=k+1; i<elements.length; i++){
                  difference = Math.abs(elements[k] - elements[i]);
                  System.out.printf("elements[%d] - elements[%d] : %d\n", k, i, difference);
                  if(difference > maximumDifference){
                      this.maximumDifference = difference;
                  }
                  System.out.println("maximumDifference (for) : " + maximumDifference);
              } //end for i
          } //end for k
          System.out.println("maximumDifference (exit.for) : " + maximumDifference);
      } //end computeDifference()
// End of Difference class
cs

결과 : 

maximumDifference (before.for) : 1

---------------------elements.length : 3

elements[0] - elements[1] : 1

maximumDifference (for) : 1

elements[0] - elements[2] : 4

maximumDifference (for) : 4

elements[1] - elements[2] : 3

maximumDifference (for) : 4

maximumDifference (exit.for) : 4

4



결과

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
30
31
32
33
34
35
36
37
class Difference {
      private int[] elements;
      public int maximumDifference;
 
      Difference(int[] elements){
          this.elements = elements;
      } //end constructor
      
      void computeDifference(){
          this.maximumDifference=0;
          int difference;
          for(int k=0; k<elements.length; k++){
              for(int i=k+1; i<elements.length; i++){
                  difference = Math.abs(elements[k] - elements[i]);
                  if(difference > maximumDifference){
                      this.maximumDifference = difference;
                  }
              } //end for i
          } //end for k
      } //end computeDifference()
// End of Difference class
 
public class Solution {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        sc.close();
        Difference difference = new Difference(a);
        difference.computeDifference();
        System.out.print(difference.maximumDifference);
    }
}
cs

결과 : 

4


+ Recent posts