https://www.acmicpc.net/problem/14246
14246번: K보다 큰 구간
n개의 자연수로 이루어진 수열이 주어질 때, 특정 구간 [i,j](i≤j)의 합이 k보다 큰 모든 쌍 i,j의 개수를 출력하시오.
www.acmicpc.net
package BOJ.twopoint;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_14246 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
int[] arr = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++){
arr[i] = stoi.apply(st.nextToken());
}
int k = stoi.apply(br.readLine());
int startIndex = 0;
int endIndex = 0;
long sum = 0;
long result = 0;
while(true){
if(sum > k){
result += n - endIndex + 1;
sum -= arr[startIndex++];
}else if(endIndex >= n){
break;
}else{ // sum < k
sum += arr[endIndex++];
}
}
System.out.println(result);
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 유한소수 판별하기 (JAVA) (0) | 2023.01.21 |
---|---|
백준 13702번 이상한 술집 (JAVA) (0) | 2023.01.20 |
백준 6159번 코스튬 파티 (JAVA) (0) | 2023.01.19 |
백준 11581번 구호물자(JAVA) (0) | 2023.01.17 |
백준 15558번 점프 게임 (JAVA) (0) | 2023.01.16 |