주녘공부일지

[프로그래머스 C#] Lv.2 연속된 부분 수열의 합 본문

Programmers - C#/CodingTest Lv.2

[프로그래머스 C#] Lv.2 연속된 부분 수열의 합

주녘 2023. 8. 30. 15:08
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/178870

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

가장 짧은 길이의 조건을 만족하는 부분 수열의 합을 구하는 문제.

- Queue에는 가장 큰 수부터 입력되고, queue 안의 모든 요소의 합이 k보다 커지면 가장 큰 수를 지워나감

 

+ Queue<T>

https://godgjwnsgur7.tistory.com/46

 

[C#] 자료구조 정리 (Dict, List, Queue, Stack, HashSet 등)

자료구조(Data Structure)란? 데이터를 효율적으로 접근하고 조작할 수 있게 데이터 구조를 만들어 관리하는 것 - Collections은 C#에서 지원하는 자료구조 클래스 using System.Collections.Generic; 제네릭 컬렉

godgjwnsgur7.tistory.com

    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Solution
    {
        public int[] solution(int[] sequence, int k)
        {
            Queue<int> queue = new Queue<int>();

            // 제일 큰 수부터 확인
            for (int i = sequence.Length - 1; i >= 0; i--)
            {
                if (queue.Sum() > k)
                    queue.Dequeue();

                queue.Enqueue(sequence[i]);

                if (queue.Sum() == k)
                {
                    // 만약, queue의 제일 큰 수와 다음 확인 예정인 수가 같을 때
                    if (i > 0 && sequence[i - 1] == queue.Peek())
                        while (i > 0 && sequence[i - 1] == queue.Peek())
                            i--;

                    return new int[2] { i, i + queue.Count - 1 };
                }
            }

            return new int[2] { -1, -1 };
        }
    }
728x90