Hyunebee

최대의 합 본문

카테고리 없음

최대의 합

Hyunebee 2022. 5. 18. 23:29

연속된 숫자 K개 중 합이 가장커지는 경우를 구하여라 -> slide window 사용

 

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      int arrL = sc.nextInt();// 배열의 크기
      int window = sc.nextInt(); // K 의 크기


      int[] arr = new int[arrL];
      for(int i = 0; i < arrL; i++){
        arr[i] = sc.nextInt();
      }
      Main T = new Main();


      System.out.println(T.solution(arr , window));

    }

    public int solution(int[] arr, int k){


      int result = 0;

      for(int i = 0 ; i < k; i++){
        result +=arr[i]; // K개 까지의 합 
      }


      int anwser = result;// 기존 합과 새로운 합을 비교할 객체가 필요함
      for(int i = k; i < arr.length; i++){
        result = result + (arr[i] - arr[i-k]);//

        anwser = Math.max(anwser,result);
      }

      return anwser;
    }
}