java 中列表的子列表

Sublists of a list in java

某一维景观中有N座建筑物。每个建筑物的高度由 hi,i∈[1,N] 给出。如果将相邻的K栋建筑物连接起来,它们将形成一个面积为K×min(hi,hi+1,…,hi+k−1)的实心矩形。

给定N栋建筑物,找出连续建筑物形成的最大实心区域。

输入格式 第一行包含 N,建筑物的总数。 第二行包含N个space分隔的整数,每个整数代表建筑物的高度。

输出格式 一个整数代表所形成的矩形的最大面积。

示例输入

5
1 2 3 4 5

示例输出

9

这是我的代码,我试图交叉检查它但它有问题,每当我访问子列表时,它会自动排序并且它们在原始列表中的位置也会发生变化

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

 public class Solution 
{
 public static void main(String[] args) 
 {
   Scanner sc = new Scanner(System.in);
   int n=sc.nextInt();

   List<Integer> al= new ArrayList<Integer>();

    for(int i=0;i<n;i++)
        al.add(sc.nextInt());

  int i, c,min=0;

  for( c = 0 ; c < n ; c++ )
  {

     for( i = c+1 ; i <= n ; i++ )
     {   
         System.out.println(" value of c is "+c+" value of i is "+i);
         List<Integer> X = al.subList(c,i);

         for(int j=0;j<X.size();j++)
             System.out.print(X.get(j)+" ");

         System.out.println();

         Collections.sort(X);

         for(int j=0;j<X.size();j++)
             System.out.print(X.get(j)+" ");

         System.out.println();

         int x=X.get(0);
         System.out.println("min value is "+x);
         int y=x*(X.size());
         System.out.println("projected value is "+y);

         if(y > min)
             min = y;

         System.out.println("modified value is "+min);

      }
   }

    System.out.println(min);
  }
}

实际上明确记录了 subList() 方法,为您提供 视图 原始的:

Returns a view of the portion of this list between the specified * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If * {@code fromIndex} and {@code toIndex} are equal, the returned list is * empty.) The returned list is backed by this list, so non-structural * changes in the returned list are reflected in this list, and vice-versa. * The returned list supports all of the optional list operations.

所以subList()如果你想修改它而不是反映原来的变化是不合适的。

而是进行显式复制:

List<Integer> X = new ArrayList<>(al.subList(c,i));