[C++] 객지프 Code21 해결필요

유빈·2024년 3월 9일
0

C++

목록 보기
5/12
post-thumbnail

1. 문제

권오흠 교수님 객체지향프로그래밍 code21

n개의 정수를 입력받아 배열에 저장한다. 이들 중에서 1개 이상의 연속된 정수들을 더하여 얻을 수 있는 최대값을 구하여 출력하는 프로그램을 작성하여라.

입력
13
-2 3 5 -14 12 3 -9 8 -1 13 2 -5 4

출력
28


#include <iostream>
#include <algorithm>
#include <limits>

using namespace std;
const int MAX = 100;

int main() {
    int n;
    int max_total = numeric_limits<int>::min();
    int data[MAX];
    
    cin >> n;

    for (int i = 0; i < n; i++) 
        cin >> data[i];
    

    for (int j = 1; j <= n; j++) {   // 더할 개수
        for (int k = 0; k < n; k++) {   // 시작 인덱스
            int total = 0;
            for (int p = k; p < k+j; p++) {
                total += data[p];
            }
            max_total = max(max_total, total);
        }
    }
    cout << "The max sum is " << max_total << endl;

    return 0;
}

처음에는 문제를 보고 위와 같이 작성하였는데 결과값이 이상하게 나온다.



#include <iostream>
#include <algorithm>
#include <limits>

using namespace std;
const int MAX = 100;

int main() {
    int n;
    int max_total = numeric_limits<int>::min();
    int data[MAX];
    
    cin >> n;

    for (int i = 0; i < n; i++) 
        cin >> data[i];
    
    for (int j = 0; j < n; j++) {   // 시작 인덱스
        int total = 0;
        for (int k = j; k < n; k++) {  
            total += data[k];
            max_total = max(max_total, total);
        }
    }

    cout << "The max sum is " << max_total << endl;

    return 0;
}

위와 같이 작성하면 올바르게 답이 나온다.
무엇이 잘못된 것인지는 다시 고민해보고 글 써야겠다..🤔


profile
🌱

0개의 댓글