01-09 18:44
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_29 ์ตœ๋Œ€ ๊ธธ์ด ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_29 ์ตœ๋Œ€ ๊ธธ์ด ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด

miinsun 2022. 1. 4. 13:07

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

0๊ณผ 1๋กœ ๊ตฌ์„ฑ๋œ ๊ธธ์ด๊ฐ€ N์ธ ์ˆ˜์—ด์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์—ฌ๋Ÿฌ๋ถ„์€ ์ด ์ˆ˜์—ด์—์„œ ์ตœ๋Œ€ k๋ฒˆ์„ 0์„ 1๋กœ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์—ฌ๋Ÿฌ๋ถ„์ด ์ตœ๋Œ€ k๋ฒˆ์˜ ๋ณ€๊ฒฝ์„ ํ†ตํ•ด ์ด ์ˆ˜์—ด์—์„œ 1๋กœ๋งŒ ๊ตฌ์„ฑ๋œ ์ตœ๋Œ€ ๊ธธ์ด์˜ ์—ฐ์†๋ถ€๋ถ„์ˆ˜์—ด์„ ์ฐพ๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

๋งŒ์•ฝ ๊ธธ์ด๊ฐ€ ๊ธธ์ด๊ฐ€ 14์ธ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ˆ˜์—ด์ด ์ฃผ์–ด์ง€๊ณ  k=2๋ผ๋ฉด
1 1 0 0 1 1 0 1 1 0 1 1 0 1

์—ฌ๋Ÿฌ๋ถ„์ด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” 1์ด ์—ฐ์†๋œ ์—ฐ์†๋ถ€๋ถ„์ˆ˜์—ด์€
1 1 0 0 1 1 1 1 1 1 1 1 0 1
์ด๋ฉฐ ๊ทธ ๊ธธ์ด๋Š” 8 ์ž…๋‹ˆ๋‹ค.

 

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ์ˆ˜์—ด์˜ ๊ธธ์ด์ธ ์ž์—ฐ์ˆ˜ N(5<=N<100,000)์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

๋‘ ๋ฒˆ์งธ ์ค„์— N๊ธธ์ด์˜ 0๊ณผ 1๋กœ ๊ตฌ์„ฑ๋œ ์ˆ˜์—ด์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

14 2
1 1 0 0 1 1 0 1 1 0 1 1 0 1

์ถœ๋ ฅ - ์ฒซ ์ค„์— ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ์ถœ๋ ฅํ•˜์„ธ์š”.

8

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {

	public int solution(int n, int k, int [] arr) {
		int answer = 0, cnt = 0, lt = 0;
		
		for(int rt = 0; rt < n; rt++) {
			if(arr[rt] == 0) cnt++;
			
			while(cnt > k) {
				if(arr[lt] == 0) cnt--;
				lt++;
			}
			answer = Math.max(answer, rt - lt + 1);
		}
		
        return answer;
	}
	
	public static void main(String[] args){
		Main main  = new Main();
		Scanner sc =new Scanner(System.in);
		
		int n = sc.nextInt();
		int k = sc.nextInt();
		int [] arr = new int [n];
		
		for(int i = 0; i < n; i++)
			arr[i] = sc.nextInt();
		
		System.out.println(main.solution(n, k, arr));
		
		sc.close();
		return ;
	}
}

 

 

 

Comments