백준 10211번 Maximum Subarray

honeyricecake·2022년 3월 7일
0

백준

목록 보기
25/30

나의 아이디어 및 코드

처음에 들어오는 값을 max와 total로 한다.
total이 음수가 되면 그 전 값들은 있느니만 못하므로(?) 그 때마다 0으로 초기화해준다.

그리고 현재 max와 total을 계속 비교하여 max보다 total이 크면 그 값을 max로 하고, 마지막에 max값을 출력한다.

#include <stdio.h>

int main()
{
	int i, j, N, T;
	int x;
	int total;
	int max;
	scanf("%d", &T);
	for (i = 0; i < T; i++)
	{
		scanf("%d", &N);

		scanf("%d", &x);
		total = x;
		max = x;

		for (j = 1; j < N; j++)
		{
			scanf("%d", &x);
			if (total < 0) total = 0;
			total += x;
			max = max < total ? total : max;
		}
		
		printf("%d\n", max);

	}
	return 0;
}

0개의 댓글