Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

arrays - Checking monotonic sequences - C programming

I am doing a problem about checking monotonic sequences. The problem is inputting a sequence and then print "YES" if it is monotonic, "NO" if it is not.

This is my code:

#include <stdio.h>

int main()
{
    //Inputting the sequence
    int n;
    scanf("%d", &n);
    int a[n];
    for (int i = 1; i <= n; i++)
    {
        scanf("%d ", &a[i]);
    }

    
    //Checking monotonic sequence
    for (int i = 1; i <= n; i++)
    {
        if ((a[i] > a[i-1]) && (a[i] > a[i+1]))
            {
                printf("NO");
                return;
            }
        else if ((a[i] < a[i-1]) && (a[i] < a[i+1]))
            {
                printf("NO");
                return;
            }
        
    }
    printf("YES");

    return 0;
}

I have failed 2 test case with sequences [1, 2, 3] and [10, 6, 4, 2, 1, -100]; and passed one test case with [1, 2, 3, 3, 2, 1]. Can anyone please point out the problem in my code? I would truly appreciate that. Thank you.

question from:https://stackoverflow.com/questions/65644217/checking-monotonic-sequences-c-programming

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Remove trailing " ". It obliges additional input (or end-of-file) after the number is entered before scanf() returns.

// scanf("%d ", &a[i]);
scanf("%d", &a[i]);

In addition to index problems in 2 places, code needs to look for overall monotonic and not just local monotonic behavior.

bool up = true;
bool down = true;

// for (int i = 1; i <= n; i++)
for (int i = 1; i < n; i++) {
  if (a[i] > a[i-1]) down = false;
  if (a[i] < a[i-1]) up = false;
}

printf((up || down) ? "YES" : "NO");

Additional code to short-circuit loop.

// for (int i = 1; i < n; i++) {
for (int i = 1; i < n && (up || down); i++) {

Further there is lack of the coding goal clarity on tie cases. May need

  if (a[i] >= a[i-1]) down = false;
  if (a[i] <= a[i-1]) up = false;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...