1 minute read

Birthday Chocolate (Hacker Rank)

Lily has a chocolate bar consisting of a row of squares where each square has an integer written on it. She wants to share it with Ron for his birthday, which falls on month and day . Lily wants to give Ron a piece of chocolate only if it contains consecutive squares whose integers sum to .

Given , , and the sequence of integers written on each square of Lily’s chocolate bar, how many different ways can Lily break off a piece of chocolate to give to Ron?

For example, if , and the chocolate bar contains rows of squares with the integers written on them from left to right, the following diagram shows two ways to break off a piece:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int solve(int n, int[] s, int d, int m){
        int result = 0, sum;
        for(int i=0; i < n; i++){
            sum = 0;
            for(int j=0; j < m; j++){
                int idx = i + j;
                if(idx < n){
                    sum += s[idx];
                }
            }
            if(sum == d){
                result++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] s = new int[n];
        for(int s_i=0; s_i < n; s_i++){
            s[s_i] = in.nextInt();
        }
        int d = in.nextInt();
        int m = in.nextInt();
        int result = solve(n, s, d, m);
        System.out.println(result);
    }
}
행운의 77문제 프로젝트
  행운의 77문제 프로젝트는 한 달동안 알고리즘 문제 77개를 푸는 프로젝트입니다.