๐Ÿ“ฆ1806: subtotal


[์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด] ๊ฐ•๋™๊ทœ
Reviewed by Kade Kang (devkade12@gmail.com)
Reviewed:: 2024-02-19
๋ฌธ์ œ ํ™•์ธํ•˜๊ธฐ

ํ’€์ด

  • ์ด์ค‘ for ๋ฌธ์„ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ sum์„ ์ฒ˜์Œ๋ถ€ํ„ฐ ์ƒˆ๋กœ ๋”ํ•ด๊ฐ€๋ฉด์„œ ๊ตฌํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.
  • ๋•Œ๋ฌธ์— sum, ๋ˆ„์ ํ•ฉ์„ ๊ฐฑ์‹ ํ•ด์ค˜์•ผ ํ•œ๋‹ค.
  • start, end๊ฐ€ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ start๋Š” end๊นŒ์ง€, end๋Š” N๊นŒ์ง€๋กœ ๋ฒ”์œ„๋ฅผ ์ง€์ •ํ•œ๋‹ค.
  • ์ด ์•ˆ์—์„œ ๋ชฉํ‘œ๊ฐ’๊นŒ์ง€ ๋„๋‹ฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด end๋ฅผ ๋Š˜๋ ค ๋ชฉํ‘œ๊ฐ’์„ ๋„˜๊ธธ ์ˆ˜ ์žˆ๋„๋ก ๋งŒ๋“ค๊ณ  ๋ชฉํ‘œ๊ฐ’์— ๋„๋‹ฌํ•˜๋ฉด start๋ฅผ ๋Š˜๋ ค ์ตœ์†Œ ๋ฒ”์œ„๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ๋„๋ก ํ•œ๋‹ค.
#include <iostream>
 
#define endl '\n'
using namespace std;
 
int N, S;
int arr[100001];
int res, sum=0;
 
void Input(){
    cin >> N >> S;
    for(int i=0; i<N; i++){
        cin >> arr[i];
    }
}
 
void Solution(){
    res = INT32_MAX;
    sum = arr[0];
    int start = 0;
    int end = 0;
    while(start <= end && end < N){
        if(sum >= S) res = min(res, end-start+1);
        if(sum < S){
            end++;
            sum += arr[end];
        }
        else{
            sum -= arr[start];
            start++;
        }
    }
    if(res == INT32_MAX) cout << 0 << endl;
    else cout << res << endl;
}
 
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
 
    Input();
    Solution();
 
    return 0;
}