태그 : two pointer

부분합

문제

10,000 이하의 자연수로 이루어진 길이 N짜리 수열이 주어진다. 이 수열에서 연속된 수들의 부분합 중에 그 합이 S 이상이 되는 것 중, 가장 짧은 것의 길이를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N (10 ≤ N < 100,000)과 S (0 < S ≤ 100,000,000)가 주어진다. 둘째 줄에는 수열이 주어진다. 수열의 각 원소는 공백으로 구분되어져 있으며, 10,000이하의 자연수이다.

10 15
5 1 3 5 10 7 4 9 2 8
출력

첫째 줄에 구하고자 하는 최소의 길이를 출력한다. 만일 그러한 합을 만드는 것이 불가능하다면 0을 출력하면 된다.

2
👍 #1. 풀이확인 js with readline 👍
 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const readline = require('readline')
const r = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

const getResult = (N, S, Arr) => {
  let start = 0
  let end = 0
  let sum = Arr[end]
  let result = 0
  let count = 0
  while (start <= end && end < Arr.length) {
    const length = end - start + 1
    if (sum === S) {
      if (result === 0) {
        result = length
      } else {
        result = result <= length ? result : length
      }
      end++
      sum += Arr[end]
    } else if (sum < S) {
      end++
      sum += Arr[end]
    } else {
      if (result === 0) {
        result = length
      } else {
        result = result <= length ? result : length
      }
      sum -= Arr[start]
      start++
    }
  }
  console.log(result)
}

let input = []

r.on('line', line => {
  input.push(line.trim())
  if (input.length === 2) {
    const N = parseInt(input[0].split(' ')[0], 10)
    const S = parseInt(input[0].split(' ')[1], 10)
    const Arr = input[1].split(' ').map(i => parseInt(i, 10))
    getResult(N, S, Arr)
    input.length = 0
  }
})
 .on('close', () => {process.exit()})
👍 #1. 풀이확인 js with readFileSync 👍
 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
let input = require("fs").readFileSync('/dev/stdin').toString().trim().split('\n');
const N = parseInt(input[0].split(' ')[0], 10)
const S = parseInt(input[0].split(' ')[1], 10)
const Arr = input[1].split(' ').map(i => parseInt(i, 10))
const getResult = (N, S, Arr) => {
  let start = 0
  let end = 0
  let sum = Arr[end]
  let result = 0
  let count = 0
  while (start <= end && end < Arr.length) {
    const length = end - start + 1
    if (sum === S) {
      if (result === 0) {
        result = length
      } else {
        result = result <= length ? result : length
      }
      end++
      sum += Arr[end]
    } else if (sum < S) {
      end++
      sum += Arr[end]
    } else {
      if (result === 0) {
        result = length
      } else {
        result = result <= length ? result : length
      }
      sum -= Arr[start]
      start++
    }
  }
  console.log(result)
}

getResult(N, S, Arr)

백준에서 문제를 풀때는 readline보다 readFileSync를 활용하는게 시간이나 공간 비용이 적긴하지만 readline을 우선으로 사용하자.

◀️ 소수의 연속합 수들의 합2 ▶️
comments powered by Disqus