@NotNull
  private Rectangle optimizeRowsCountInVisibleRect(int @NotNull [] rows) {
    // a simple scan-line algorithm to find an optimal subset of visible rows (maximum)
    final Rectangle visibleRect = getVisibleRect();
    final int height = visibleRect.height;

    class Result {
      private int top = 0;
      private int bot = 0;

      @Contract(pure = true)
      private int count() {
        return bot - top;
      }
    }

    int topIndex = 0;
    int bottomIndex = 1;
    Rectangle rowBounds = getRowBounds(rows[topIndex]);
    if (rowBounds == null) return visibleRect;
    int topY = rowBounds.y;

    final Result result = new Result();
    while (bottomIndex < rows.length) {
      final int nextY = getRowBounds(rows[bottomIndex]).y;
      while (nextY - topY > height) {
        topIndex++;
        rowBounds = getRowBounds(rows[topIndex]);
        if (rowBounds == null) return visibleRect;
        topY = rowBounds.y;
      }

      if (bottomIndex - topIndex > result.count()) {
        result.top = topIndex;
        result.bot = bottomIndex;
      }

      bottomIndex++;
    }

    int y = getRowBounds(rows[result.top]).y;
    if (y > visibleRect.y) {
      final Rectangle botBounds = getRowBounds(rows[result.bot]);
      y = botBounds.y + botBounds.height - visibleRect.height;
    }
    return new Rectangle(visibleRect.x, y, visibleRect.width, height);
  }
@NotNull
  private Rectangle optimizeRowsCountInVisibleRect(int @NotNull [] rows)