public static IdeaPluginDescriptorImpl[] loadDescriptors(@Nullable StartupProgress progress) { if (ClassUtilCore.isLoadingOfExternalPluginsDisabled()) { return IdeaPluginDescriptorImpl.EMPTY_ARRAY; } final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); int pluginsCount = countPlugins(PathManager.getPluginsPath()) + countPlugins(PathManager.getPreinstalledPluginsPath()); loadDescriptors(PathManager.getPluginsPath(), result, progress, pluginsCount); Application application = ApplicationManager.getApplication(); boolean fromSources = false; if (application == null || !application.isUnitTestMode()) { int size = result.size(); loadDescriptors(PathManager.getPreinstalledPluginsPath(), result, progress, pluginsCount); fromSources = size == result.size(); } loadDescriptorsFromProperty(result); loadDescriptorsFromClassPath(result, fromSources ? progress : null); IdeaPluginDescriptorImpl[] pluginDescriptors = result.toArray(new IdeaPluginDescriptorImpl[result.size()]); try { Arrays.sort(pluginDescriptors, new PluginDescriptorComparator(pluginDescriptors)); } catch (Exception e) { prepareLoadingPluginsErrorMessage( IdeBundle.message("error.plugins.were.not.loaded", e.getMessage())); getLogger().info(e); return findCorePlugin(pluginDescriptors); } return pluginDescriptors; }
public void setSwingDataCollection(Collection<ICFSecurityISOCountryObj> value) { final String S_ProcName = "setSwingDataCollection"; swingDataCollection = value; if (swingDataCollection == null) { arrayOfISOCountry = new ICFSecurityISOCountryObj[0]; } else { int len = value.size(); arrayOfISOCountry = new ICFSecurityISOCountryObj[len]; Iterator<ICFSecurityISOCountryObj> iter = swingDataCollection.iterator(); int idx = 0; while (iter.hasNext() && (idx < len)) { arrayOfISOCountry[idx++] = iter.next(); } if (idx < len) { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Collection iterator did not fully populate the array copy"); } if (iter.hasNext()) { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Collection iterator had left over items when done populating array copy"); } Arrays.sort(arrayOfISOCountry, compareISOCountryByQualName); } PickerTableModel tblDataModel = getDataModel(); if (tblDataModel != null) { tblDataModel.fireTableDataChanged(); } }
/** * Creates a new <code>AnnotationDirectoryItem</code> with the given values * * @param dexFile The <code>DexFile</code> that this item belongs to * @param classAnnotations The annotations associated with the overall class * @param fieldAnnotations A list of <code>FieldAnnotation</code> objects that contain the field * annotations for this class * @param methodAnnotations A list of <code>MethodAnnotation</code> objects that contain the * method annotations for this class * @param parameterAnnotations A list of <code>ParameterAnnotation</code> objects that contain the * parameter annotations for the methods in this class */ private AnnotationDirectoryItem( DexFile dexFile, @Nullable AnnotationSetItem classAnnotations, @Nullable List<FieldAnnotation> fieldAnnotations, @Nullable List<MethodAnnotation> methodAnnotations, @Nullable List<ParameterAnnotation> parameterAnnotations) { super(dexFile); this.classAnnotations = classAnnotations; if (fieldAnnotations == null || fieldAnnotations.size() == 0) { this.fieldAnnotations = null; } else { this.fieldAnnotations = new FieldAnnotation[fieldAnnotations.size()]; this.fieldAnnotations = fieldAnnotations.toArray(this.fieldAnnotations); Arrays.sort(this.fieldAnnotations); } if (methodAnnotations == null || methodAnnotations.size() == 0) { this.methodAnnotations = null; } else { this.methodAnnotations = new MethodAnnotation[methodAnnotations.size()]; this.methodAnnotations = methodAnnotations.toArray(this.methodAnnotations); Arrays.sort(this.methodAnnotations); } if (parameterAnnotations == null || parameterAnnotations.size() == 0) { this.parameterAnnotations = null; } else { this.parameterAnnotations = new ParameterAnnotation[parameterAnnotations.size()]; this.parameterAnnotations = parameterAnnotations.toArray(this.parameterAnnotations); Arrays.sort(this.parameterAnnotations); } }
@Test public void valuesToArray() { HazelcastClient hClient = getHazelcastClient(); IMap map = hClient.getMap("valuesToArray"); assertEquals(0, map.size()); map.put("a", "1"); map.put("b", "2"); map.put("c", "3"); assertEquals(3, map.size()); { final Object[] values = map.values().toArray(); Arrays.sort(values); assertArrayEquals(new Object[] {"1", "2", "3"}, values); } { final String[] values = (String[]) map.values().toArray(new String[3]); Arrays.sort(values); assertArrayEquals(new String[] {"1", "2", "3"}, values); } { final String[] values = (String[]) map.values().toArray(new String[2]); Arrays.sort(values); assertArrayEquals(new String[] {"1", "2", "3"}, values); } { final String[] values = (String[]) map.values().toArray(new String[5]); Arrays.sort(values, 0, 3); assertArrayEquals(new String[] {"1", "2", "3", null, null}, values); } }
public static long sumsLowerBound(long[] a, long b) { int n = a.length; int sizeL = 1 << (n / 2); int sizeR = 1 << (n - n / 2); long[] sumsL = new long[sizeL]; long[] sumsR = new long[sizeR]; for (int i = 0; i < sizeL; ++i) for (int j = 0; j < n / 2; ++j) if ((i & (1 << j)) > 0) sumsL[i] += a[j]; for (int i = 0; i < sizeR; ++i) for (int j = 0; j < n - n / 2; ++j) if ((i & (1 << j)) > 0) sumsR[i] += a[j + n / 2]; Arrays.sort(sumsL); Arrays.sort(sumsR); int left = 0; int right = sizeR - 1; long cur = Long.MIN_VALUE; while (left < sizeL && right >= 0) { if (sumsL[left] + sumsR[right] <= b) { cur = Math.max(cur, sumsL[left] + sumsR[right]); ++left; } else { --right; } } return cur; }
public static boolean checkAnagrams(String str1, String str2) { char[] str1arr = str1.toCharArray(); char[] str2arr = str2.toCharArray(); Arrays.sort(str1arr); Arrays.sort(str2arr); return Arrays.equals(str1arr, str2arr); }
public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(), m = input.nextInt(); int[] data = new int[m], data2 = new int[m]; for (int i = 0; i < m; i++) { data[i] = input.nextInt(); data2[i] = data[i]; } Arrays.sort(data); Arrays.sort(data2); // find min int at = 0, min = 0, max = 0, needed = n; while (needed > 0) { min += data[at]; data[at]--; needed--; if (data[at] == 0) at++; } needed = n; while (needed > 0) { needed--; max += data2[m - 1]; data2[m - 1]--; Arrays.sort(data2); } System.out.println(max + " " + min); }
// Write a method that determines if two strings are anagrams of each other. For example, “TEAM” // and “MEAT” would return true. public static boolean isAnagram(String a, String b) { // Remove whitespace using a regular expression a = a.replaceAll("\\s+", ""); b = b.replaceAll("\\s+", ""); // Change to uppercase to reduce amount of possible characters a = a.toUpperCase(); b = b.toUpperCase(); // Turn the string into char arrays char i[] = a.toCharArray(); char j[] = b.toCharArray(); // Sort the arrays Arrays.sort(i); Arrays.sort(j); // Now check for equality for (int c = 0; c < i.length; c++) { // Since these are sorted, the indicies should match up. if (i[c] != j[c]) { return false; } // if } // for // Else, return true return true; } // isAnagram
public static void main(String args[]) throws Exception { Scanner keyb = new Scanner(new File("jorge.dat")); while (keyb.hasNextLine()) { String dat[] = keyb.nextLine().split(" "); int ints[] = new int[dat.length]; for (int i = 0; i < dat.length; i++) { ints[i] = Integer.parseInt(dat[i]); } int mods[] = new int[dat.length]; for (int i = 0; i < dat.length; i++) { mods[i] = Integer.parseInt(dat[i]) % 13; } Arrays.sort(ints); Arrays.sort(mods); System.out.println(Arrays.toString(ints)); if (asd(mods)) { System.out.println("FOUR OF A KIND"); } else if (dannyTanner(mods)) { System.out.println("FULL HOUSE"); } else if (toilet(ints)) { System.out.println("FLUSH"); } else if (yag(ints, mods) { System.out.println("STRAIGHT"); } else if (tres()) { } }
boolean checkSameChar(char[] s1, char[] s2) { s1 = Arrays.copyOf(s1, s1.length); s2 = Arrays.copyOf(s2, s2.length); Arrays.sort(s1); Arrays.sort(s2); return Arrays.equals(s1, s2); }
public boolean isAnagram(String s, String t) { if (s == null || s == "" || t == null || t == "") return false; if (s.length() != t.length()) return false; char[] arr1 = s.toCharArray(); char[] arr2 = t.toCharArray(); Arrays.sort(arr1); Arrays.sort(arr2); // sorted arrays should be identical return Arrays.equals(arr1, arr2); }
@Test public void testNnclean() throws Exception { double[] y = HET_DEL_5X_5N; double[] nonnoise = new double[] {260.0736, 197.4272, 194.8618, 1217.8588, 1228.2190, 1151.7017}; double[] result = scorer.nnclean(y, scorer.cleanYIndices(y, 30, 2, 5)); Arrays.sort(result); Arrays.sort(nonnoise); assertArrayEquals(nonnoise, result, 0.000001); }
public Cedars(String args[]) throws ArchiveException, IOException, HoneycombTestException { verbose = false; parseArgs(args); initHCClient(host); // generate lists of random sizes around 30M and 3M // sort ascending to allow continuous expansion try { initRandom(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } sizes = new long[n_files]; for (int i = 0; i < sizes.length; i++) { sizes[i] = MIN_SIZE + (long) (rand.nextDouble() * (double) RANGE); } Arrays.sort(sizes); sizes2 = new long[n_files]; for (int i = 0; i < sizes2.length; i++) { sizes2[i] = MIN_SIZE2 + (long) (rand.nextDouble() * (double) RANGE2); } Arrays.sort(sizes2); sizes3 = new long[n_files]; for (int i = 0; i < sizes3.length; i++) { sizes3[i] = MIN_SIZE3 + (long) (rand.nextDouble() * (double) RANGE3); } Arrays.sort(sizes3); oids = new String[n_files]; Arrays.fill(oids, null); shas = new String[n_files]; Arrays.fill(shas, null); if (out_file != null) { try { String host = clnthost; fo = new FileWriter(out_file, true); // append=true flog("#S Cedars [" + host + "] " + new Date() + "\n"); } catch (Exception e) { System.err.println("Opening " + out_file); e.printStackTrace(); System.exit(1); } } Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown(), "Shutdown")); doIt(); done = true; }
private static boolean isSame(String n1, String n2) { if (n1.length() != n2.length()) return false; char[] first = n1.toCharArray(); char[] secound = n2.toCharArray(); Arrays.sort(first); Arrays.sort(secound); for (int i = 0; i < first.length; i++) { if (first[i] != secound[i]) return false; } return true; }
public static boolean permutation0(String str1, String str2) { if (str1.length() != str2.length()) return false; char[] array1 = str1.toCharArray(); char[] array2 = str2.toCharArray(); Arrays.sort(array1); Arrays.sort(array2); if (new String(array1).equals(new String(array2))) return true; return false; }
public List<List<String>> groupAnagrams(String[] strs) { Arrays.sort(strs); Map<String, List<String>> ans = new HashMap<>(); for (String str : strs) { char[] cs = str.toCharArray(); Arrays.sort(cs); String key = new String(cs); List<String> lt = ans.getOrDefault(key, new ArrayList<>()); lt.add(str); ans.put(key, lt); } return new ArrayList<>(ans.values()); }
private static String keyTransform(String note, int key) { if (note.length() == 3) return note; if (key < 0) { char[] flatRange = Arrays.copyOfRange(circleOfFifths, 7 + key, 7); Arrays.sort(flatRange); if (Arrays.binarySearch(flatRange, note.charAt(0)) >= 0) return note.concat("@"); } if (key > 0) { char[] sharpRange = Arrays.copyOfRange(circleOfFifths, 0, key); Arrays.sort(sharpRange); if (Arrays.binarySearch(sharpRange, note.charAt(0)) >= 0) return note.concat("#"); } return note; }
/** * Paint to an offscreen graphic, e.g. a graphic for an image or svg file. * * @param g * @param rect */ public void paintOffscreen(Graphics2D g, Rectangle rect) { // Get the components of the sort by X position. Component[] components = getComponents(); Arrays.sort( components, new Comparator<Component>() { public int compare(Component component, Component component1) { return component.getX() - component1.getX(); } }); for (Component c : this.getComponents()) { if (c instanceof DataPanel) { Graphics2D g2d = (Graphics2D) g.create(); Rectangle clipRect = new Rectangle(c.getBounds()); clipRect.height = rect.height; g2d.setClip(clipRect); g2d.translate(c.getX(), 0); ((DataPanel) c).paintOffscreen(g2d, rect); } } // super.paintBorder(g); }
public static void recover() throws IOException { String directory = DatabaseDescriptor.getCommitLogLocation(); File[] files = new File(directory) .listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { return CommitLogSegment.possibleCommitLogFile(name); } }); if (files.length == 0) return; Arrays.sort(files, new FileUtils.FileComparator()); logger.info("Replaying " + StringUtils.join(files, ", ")); recover(files); for (File f : files) { FileUtils.delete( CommitLogHeader.getHeaderPathFromSegmentPath( f.getAbsolutePath())); // may not actually exist if (!f.delete()) logger.error( "Unable to remove " + f + "; you should remove it manually or next restart will replay it again (harmless, but time-consuming)"); } logger.info("Log replay complete"); }
public Element toXml() { Element root = new Element(ROOT_ELEMENT); root.setAttribute(ATTR_VERSION, Integer.toString(DEPENDENCIES_VERSION)); if (myModelHash != null) { root.setAttribute(ATTR_MODEL_HASH, myModelHash); } if (myParametersHash != null) { root.setAttribute(ATTR_PARAMS_HASH, myParametersHash); } String[] models = myUsedModelsHashes.keySet().toArray(new String[myUsedModelsHashes.size()]); Arrays.sort(models); for (String model : models) { Element e = new Element(NODE_MODEL); e.setAttribute(ATTR_MODEL_ID, model); String hash = myUsedModelsHashes.get(model); if (hash != null) { e.setAttribute(ATTR_HASH, hash); } root.addContent(e); } if (myRootDependencies != null) { for (GenerationRootDependencies data : myRootDependencies) { Element e = new Element(data.getRootId() != null ? NODE_ROOT : NODE_COMMON); data.saveTo(e); root.addContent(e); } } return root; }
public NaturalBreaksClassifier(QueryResults qr, int numCategories, Color color1, Color color2) { double[] list = new double[qr.items.size()]; Iterator<QueryResults.QueryResultItem> qrIt = qr.items.values().iterator(); for (int i = 0; i < list.length; i++) { list[i] = qrIt.next().value; } Arrays.sort(list); // we can't classify into more bins than we have values if (numCategories > list.length) numCategories = list.length; double[] breaks = buildJenksBreaks(list, numCategories); if (breaks.length == 0) return; for (int i = 0; i < numCategories; i++) { // numcategories - 1: fencepost problem. The highest value should get color2 Color c; if (numCategories > 1) c = interpolateColor(color1, color2, (float) ((float) i / (float) (numCategories - 1))); else c = interpolateColor(color1, color2, 0.5f); bins.add(new Bin(breaks[i], breaks[i + 1], c)); } addPercentagesToBins(qr.maxPossible); bins.get(0).lower -= 0.00000001; bins.get(bins.size() - 1).upper += 0.00000001; }
public int minMeetingRooms(Interval[] intervals) { if (intervals == null || intervals.length == 0) return 0; Arrays.sort( intervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); PriorityQueue<Interval> heap = new PriorityQueue<Interval>( intervals.length, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.end - b.end; } }); heap.offer(intervals[0]); for (int i = 1; i < intervals.length; i++) { Interval poll = heap.poll(); if (intervals[i].start >= poll.end) poll.end = intervals[i].end; else heap.offer(intervals[i]); heap.offer(poll); } return heap.size(); }
public void solve() throws IOException { MyReader in = new MyReader(); PrintWriter out = new PrintWriter(System.out); while (true) { int n = in.nextInt(); if (n == 0) break; int m = in.nextInt(), g = in.nextInt(), score[] = new int[m]; for (int i = 0; i < m; i++) score[i] = in.nextInt(); Student students[] = new Student[n]; for (int i = 0; i < n; i++) { String name = in.next(); int cnt = in.nextInt(), totScore = 0; for (int j = 0; j < cnt; j++) totScore += score[in.nextInt() - 1]; students[i] = new Student(name, totScore); } Arrays.sort(students); int pass_cnt = 0; for (; pass_cnt < n && students[pass_cnt].getScore() >= g; pass_cnt++) ; out.println(pass_cnt); for (int i = 0; i < pass_cnt; i++) students[i].print(out); out.flush(); } }
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] str; str = in.readLine().split(" "); int N = Integer.parseInt(str[0]); long[] A = new long[N]; long[] B = new long[N]; long[] C = new long[N]; long[] D = new long[N]; for (int i = 0; i < N; i++) { str = in.readLine().split(" "); A[i] = Long.parseLong(str[0]); B[i] = Long.parseLong(str[1]); C[i] = Long.parseLong(str[2]); D[i] = Long.parseLong(str[3]); } long[] CD = new long[N * N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { CD[i * N + j] = C[i] + D[j]; } } Arrays.sort(CD); long count = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { long sum = A[i] + B[j]; count += upperbound(CD, -sum) - lowerbound(CD, -sum) + 1; } } System.out.println(count); }
@Override Val apply(Env env, Env.StackHelp stk, AST asts[]) { Val v = stk.track(asts[1].exec(env)); if (v instanceof ValRow) { ValRow vv = (ValRow) v; return vv.slice(asts[2].columns(vv._names)); } Frame fr = v.getFrame(); int[] cols = asts[2].columns(fr.names()); Frame fr2 = new Frame(); if (cols.length == 0) { // Empty inclusion list? } else if (cols[0] >= 0) { // Positive (inclusion) list if (cols[cols.length - 1] > fr.numCols()) throw new IllegalArgumentException( "Column must be an integer from 0 to " + (fr.numCols() - 1)); for (int col : cols) fr2.add(fr.names()[col], fr.vecs()[col]); } else { // Negative (exclusion) list fr2 = new Frame(fr); // All of them at first Arrays.sort(cols); // This loop depends on the values in sorted order for (int col : cols) if (0 <= -col - 1 && -col - 1 < fr.numCols()) fr2.remove(-col - 1); // Remove named column } return new ValFrame(fr2); }
public List<ICFAccTaxObj> readAllTax(boolean forceRead) { final String S_ProcName = "readAllTax"; if ((allTax == null) || forceRead) { Map<CFAccTaxPKey, ICFAccTaxObj> map = new HashMap<CFAccTaxPKey, ICFAccTaxObj>(); allTax = map; CFAccTaxBuff[] buffList = ((ICFAccSchema) schema.getBackingStore()) .getTableTax() .readAllDerived(schema.getAuthorization()); CFAccTaxBuff buff; ICFAccTaxObj obj; for (int idx = 0; idx < buffList.length; idx++) { buff = buffList[idx]; obj = newInstance(); obj.setPKey(((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newPKey()); obj.setBuff(buff); ICFAccTaxObj realized = (ICFAccTaxObj) obj.realize(); } } Comparator<ICFAccTaxObj> cmp = new Comparator<ICFAccTaxObj>() { public int compare(ICFAccTaxObj lhs, ICFAccTaxObj rhs) { if (lhs == null) { if (rhs == null) { return (0); } else { return (-1); } } else if (rhs == null) { return (1); } else { CFAccTaxPKey lhsPKey = lhs.getPKey(); CFAccTaxPKey rhsPKey = rhs.getPKey(); int ret = lhsPKey.compareTo(rhsPKey); return (ret); } } }; int len = allTax.size(); ICFAccTaxObj arr[] = new ICFAccTaxObj[len]; Iterator<ICFAccTaxObj> valIter = allTax.values().iterator(); int idx = 0; while ((idx < len) && valIter.hasNext()) { arr[idx++] = valIter.next(); } if (idx < len) { throw CFLib.getDefaultExceptionFactory() .newArgumentUnderflowException(getClass(), S_ProcName, 0, "idx", idx, len); } else if (valIter.hasNext()) { throw CFLib.getDefaultExceptionFactory() .newArgumentOverflowException(getClass(), S_ProcName, 0, "idx", idx, len); } Arrays.sort(arr, cmp); ArrayList<ICFAccTaxObj> arrayList = new ArrayList<ICFAccTaxObj>(len); for (idx = 0; idx < len; idx++) { arrayList.add(arr[idx]); } List<ICFAccTaxObj> sortedList = arrayList; return (sortedList); }
public void loadData(boolean forceReload) { ICFFreeSwitchSchemaObj schemaObj = swingSchema.getSchema(); if ((containingCluster == null) || forceReload) { CFSecurityAuthorization auth = schemaObj.getAuthorization(); long containingClusterId = auth.getSecClusterId(); containingCluster = schemaObj.getClusterTableObj().readClusterByIdIdx(containingClusterId); } if ((listOfTenant == null) || forceReload) { arrayOfTenant = null; listOfTenant = schemaObj .getTenantTableObj() .readTenantByClusterIdx(containingCluster.getRequiredId(), swingIsInitializing); if (listOfTenant != null) { Object objArray[] = listOfTenant.toArray(); if (objArray != null) { int len = objArray.length; arrayOfTenant = new ICFSecurityTenantObj[len]; for (int i = 0; i < len; i++) { arrayOfTenant[i] = (ICFSecurityTenantObj) objArray[i]; } Arrays.sort(arrayOfTenant, compareTenantByQualName); } } } }
private void sort() { final Locale loc = getLocale(); final Collator collator = Collator.getInstance(loc); final Comparator<Locale> comp = new Comparator<Locale>() { public int compare(Locale a, Locale b) { return collator.compare(a.getDisplayName(loc), b.getDisplayName(loc)); } }; Arrays.sort(locales, comp); setModel( new ComboBoxModel<Locale>() { public Locale getElementAt(int i) { return locales[i]; } public int getSize() { return locales.length; } public void addListDataListener(ListDataListener l) {} public void removeListDataListener(ListDataListener l) {} public Locale getSelectedItem() { return selected >= 0 ? locales[selected] : null; } public void setSelectedItem(Object anItem) { if (anItem == null) selected = -1; else selected = Arrays.binarySearch(locales, (Locale) anItem, comp); } }); setSelectedItem(selected); }
public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> res = new LinkedList<>(); if (num == null || num.length == 0) return res; Arrays.sort(num); for (int i = 0; i < num.length - 2; i++) { int n1 = num[i]; int l = i + 1; int r = num.length - 1; while (l < r) { if (n1 + num[l] + num[r] == 0) { List<Integer> buf = new LinkedList<>(); buf.add(n1); buf.add(num[l]); buf.add(num[r]); res.add(buf); l++; while (l < num.length && num[l] == num[l - 1]) l++; r--; while (r >= 0 && num[r] == num[r + 1]) r--; } else if (n1 + num[l] + num[r] < 0) { l++; while (l < num.length && num[l] == num[l - 1]) l++; } else { r--; while (r >= 0 && num[r] == num[r + 1]) r--; } } while (i + 1 < num.length && num[i + 1] == n1) i++; } return res; }
public int theMin(int[] init, int[] grow, int H) { int n = init.length; Item[] items = new Item[n]; for (int i = 0; i < n; i++) { items[i] = new Item(init[i], grow[i], i); } Arrays.sort(items, new GrowCompare()); int[][] dp = new int[n + 1][n + 1]; for (int t = 1; t < n + 1; t++) { for (int i = 1; i < n + 1; i++) { dp[t][i] = Math.max(dp[t - 1][i - 1] + items[i - 1].init + t * items[i - 1].grow, dp[t][i - 1]); } } for (int i = 0; i < n + 1; i++) { int v = sum(init) + i * sum(grow) - H; if (dp[i][n] >= v) { return i; } } return -1; }