프로그래머스 178870 연속된 부분 수열의 합

Jmnote (토론 | 기여)님의 2024년 1월 29일 (월) 02:23 판 (새 문서: ==개요== {{프로그래머스|레벨=2|페이지=1|분류=연습문제}} ==C++== <syntaxhighlight lang='cpp'> #include <string> #include <vector> using namespace std; vector<int>...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요[ | ]

프로그래머스 178870 연속된 부분 수열의 합

2 C++[ | ]

#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<int> sequence, int k) {
    int n = sequence.size();
    int start = 0, end = 0;
    int sum = 0;
    vector<int> answer(2, -1);
    int minLength = 1e9;
    while (start < n) {
        if (sum < k && end < n) {
            sum += sequence[end++];
        } else {
            sum -= sequence[start++];
        }
        if (sum == k) {
            if (end - start < minLength) {
                minLength = end - start;
                answer[0] = start;
                answer[1] = end - 1;
            }
        }
    }
    return answer;
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}