Given the log with missed days(represented -1), calculate the minimum and maximum number of breakouts.


My 1st INCORRECT Code

#include <iostream>

int main() {
	int N, m = 0, M, a = 0; //M = m + a
	int count[101];

	std::cin >> N;
	for (int i = 1; i <= N; i++) {
		std::cin >> count[i];
	}

	int ptr = N;
	for (int i = N; i >= 1; i--) {
		if (ptr != i) {
			if (count[i] != i - ptr - 1) {
				std::cout << -1;
				return 0;
			}
			continue;
		}

		if (count[i] > 0) {
			m++; ptr = i - count[i] - 1;
		}
		else if (count[i] == 0) {
			m++; ptr = i-1;
		}
		else { //missed
			if (count[i] != -1) { //error
				std::cout << -1;
				return 0;
			}
			else if (i == 1) {
				m++; ptr = i - 1;
			}
			else {
				a++; ptr = i - 1;
			}
		}
	}

	if (m) {
		M = m + a;
		printf("%d %d", m, M);
	}

}


comments

2020-01-17 Write down conditions on your note! And do not create unnecessary variables(like ‘ptr’) that makes me confuse.


Code after solution

#include <iostream>
using namespace std;

int main(void) {
	int log[100];
	int ans_m, ans_M;
	ans_m = ans_M = 0;

	/* write it just in case */
	cin.tie(0);
	ios_base::sync_with_stdio(0);

	int N;
	cin >> N;

	for (int i = 0; i < N; i++)
		cin >> log[i];

	//check the log from the end
	for (int i = N - 1; i >= 0; i--) {
		if (log[i] == -1) continue;
		if (log[i] > 0) {
			int days = 0;
			for (int j = i - log[i]; j < i; j++) {
				if (log[j] == -1) {
					log[j] = days;
				}
				else if (log[j] != days) {
					cout << -1;
					return 0;
				}
				days++;
			}
		}
	}
	log[0] = 0;

	for (int i = 0; i < N; i++) {
		if (log[i] == 0) ans_m++, ans_M++;
		if (log[i] == -1) ans_M++;
	}

	cout << ans_m << " " << ans_M;
}