문제: 1912번: 연속합
basic-algo-lecture/workbook/0x10.md at master · encrypted-def/basic-algo-lecture
basic-algo-lecture/workbook/0x10.md at master · encrypted-def/basic-algo-lecture
바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.
github.com
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <limits>
//#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++)
cin >> nums[i];
int answer = nums[0];
for (int i = 1; i < n; i++) {
// 현재값이랑, 이전의 연속합 + 현재값 중 더 큰 값으로 갱신
nums[i] = max(nums[i - 1] + nums[i], nums[i]);
if (nums[i] > answer)
answer = nums[i];
}
cout << answer << "\n";
return 0;
}
현재값이랑 이전의 연속합 + 현재값 중 더 큰 값으로 갱신해주면 쉽게 해결할 수 있는 문제이다.
참고자료:
Kadane's algorithm 이란? (설명)
코딩 문제를 풀다보면 이런 문제가 나옵니다. "배열 A의 요소들 중 연속된 합이 가장 큰 수를 구하시오" "배열 A의 요소들 중 연속된 합이 가장 큰 배열 요소의 범위를 구하시오" 배열 요소중 양수
hwan-shell.tistory.com