I am implementing a simple solution of the sequence to see if it's monotonic or strictly monotonic. I tried different inputs, corner/worst cases, it works, for a better presentation of the problem, the following is the specific statement of the problem.
Determine whether a sequence of number is strictly monotonic or monotonic.
Input:
Contains integer number n (2 ≤ n ≤ 10^9) - number of elements in sequence. There are n elements after it.
Output:
If sequence is strictly monotonic then write "2" else if sequence is juct monotonic then write "1" and "0" in other cases.
My code:
#include <iostream>
//#include <cmath>
using namespace std;
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, a, b, p, q, e, c; e = 0; q = 0; p = 0;
cin >> n >> a;
for (int i = 0; i < n - 1; i++)
{
cin >> b;
if (a > b) { p = 1;
if (q) { cout << 0; return 0; }
}
if (a < b) { q = 1;
if (p) { cout << 0; return 0; }
}
if (a == b) { e = 1; }
a = b;
}
if (e) { cout << 1; }
else { cout << 2; }
return 0;
}
My code though doesn't pass my university's ejudge, it gives Time Limit error. What can be wrong with my code? I mean, you have to go through all of n, this code is O(n), and n <= 10^9.