类似但又不同于最长平稳段问题 longestplateau

Given an array of integers int A[], find the length and location of the longest contiguous sequence of equal values for which the values of the elements just before and just after this sequence are smaller.
You should just print thes two numbers (first is the length and second is the starting index of plateau).
To complete the defintion, we can consider there are imaginary index positions at A[-1] and A[A.length] where A[-1] < A[0] and A[A.length] < A[A.length-1]. Therefore, the plateau can start/end at the both end of the array A. This condition guarantees the existence of a plateau. A plateau can be of length 1.
If there are multiple plateaus, print very first one.
Note: To ensure performance, the submitted program can not have more then two loops, ie. the total number of while and for statement can not be over 2. Make sure you don't while or for keyword in comment statements.
样例 java LongestPlateau 1 2 2 2 2 1

输出:
maxPlateauLen = 4
startPos = 1

样例 java LongestPlateau 1 2 2 2 2 3

输出

maxPlateauLen = 1
startPos = 5
这个通过不了

样例 java LongestPlateau 3 2 2 2 2 2 2 1 2 1 1 1 2 2 0 1 1 1 1

输出

maxPlateauLen = 4
startPos = 15
这个我的代码通过不了

这是我写的代码,求帮忙修改一下

public class LongestPlateau
{
public static void main(String[] args)
{

    int maxPlateauLen = 1;         // max record
    int maxPlateauStartPos = -1;

    // Read the terrain info from command line 
    int[] A = new int[args.length];
    for (int i = 0 ; i < args.length ; i++){
        A[i] = Integer.parseInt(args[i]);        
    }
    
    
    int curlen=1;
    for (int i=1; iif (A[i]==A[i-1]){curlen++;}
        else if ((A[i]-1])&&curlen>maxPlateauLen){maxPlateauLen=curlen;maxPlateauStartPos=i-curlen;curlen=0;}
        else if (A[i]>A[i-1]) {curlen=1;}
}


    
    System.out.println("maxPlateauLen = "  + maxPlateauLen);
    System.out.println("startPos = " + maxPlateauStartPos);

    return;
}

}

该回答引用GPT,有帮助的话请帮我点个采纳

遇到A[i] < A[i-1]时,您需要将curlen重置为1,而不是0,因为在这种情况下,curlen记录的是当前的平台长度,而不是最大平台长度。

正确代码如下:





public class LongestPlateau
{
public static void main(String[] args)
{
int maxPlateauLen = 1; // max record
int maxPlateauStartPos = -1;
 // Read the terrain info from command line 
    int[] A = new int[args.length];
    for (int i = 0 ; i < args.length ; i++){
        A[i] = Integer.parseInt(args[i]);        
    }

    int curlen=1;
    for (int i=1; i<A.length;i++){
        if (A[i]==A[i-1]){curlen++;}
        else if ((A[i]<A[i-1])&&curlen>maxPlateauLen){
            maxPlateauLen=curlen;
            maxPlateauStartPos=i-curlen;
            curlen=1;
        }
        else if (A[i]>A[i-1]) {curlen=1;}
    }

    System.out.println("maxPlateauLen = "  + maxPlateauLen);
    System.out.println("startPos = " + (maxPlateauStartPos+1));

    return;
}
}

顶顶