【问题标题】:I tried the question but im getting wrong output我尝试了这个问题,但我得到了错误的输出
【发布时间】:2022-01-16 17:02:48
【问题描述】:

给定连续 N 个建筑物的高度数组。您可以从任何建筑物开始,然后跳到相邻的右侧建筑物,直到右侧建筑物的高度小于或等于您当前建筑物的高度。找出你能做的最大跳跃次数。 输入 输入的第一行包含一个整数 N。 第二行输入包含 N 个整数,表示数组的高度。

约束: 1

class Main {
    public static void main (String[] args) {
                      // Your code here
                 Scanner sc = new Scanner(System.in);
                      int n = sc.nextInt();
                      int[]a = new int[n];
                      for(int i = 0; i<n; i++){
                          a[i] = sc.nextInt();
                      }
                      int count=1;
                      int max = a[0];
                      for(int i = 1; i<n; i++){
                          if(a[i] > max)
                          {
                              count++;
                              max = a[i];
                          }
                      }
                      System.out.println(count);

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    检查一下,

    public class Main {
            public static void main (String[] args) {
                    // Your code here
                    Scanner sc = new Scanner(System.in);
                    int n = sc.nextInt();
    
                    int previous_building_height = sc.nextInt();
                    int current_building_height = 0;
                    int count =0, max_count =0;
    
                    for(int i = 1; i<n; i++){
                            current_building_height = sc.nextInt();
                            if(current_building_height >= previous_building_height){
                                    count ++;
                            }else{
                                    max_count = max_count < count ? count : max_count;
                                    count =0;
                            }
                            previous_building_height = current_building_height;
                    }
    
                    max_count = max_count < count ? count : max_count;
                    System.out.println(max_count);
    
            }
    }
    

    您不需要保存所有建筑物的高度。在给定的建筑物中,我们只需要知道以前的建筑物高度。如果之前的建筑比现在的短,你可以跳。否则,如果您的跳跃计数器具有最高值,则保存它。接下来,您重新启动跳跃计数器。

    另外,试着给你的问题一个更好的标题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2023-02-10
      • 2020-12-12
      • 2018-04-19
      • 1970-01-01
      • 2021-03-29
      相关资源
      最近更新 更多