Thanos is presented with n stones and must select ...
Created on: September 2, 2025
Answered using GPT-5 Thinking by Chat01
Created on: September 2, 2025
Answered using GPT-5 Thinking by Chat01
Thanos is presented with n stones and must select a subset to maximize their total value. The total value of x selected stones is calculated as x multiplied by the minimum value among those x stones. What is the highest possible total Thanos can achieve?
N <= 1e5
A[i] <= 1e9
can you find this qn in internet
sorting the whole array and then taking max(ans,a[i]*(n-i)) will it work ??
If not please solve it in your way in java
Short answer: yes — that exact idea works.
If you sort the array in nondecreasing order and, for each index i, consider picking all stones from i to n-1, the minimum among those picked stones is A[i] and the count is (n - i), so the total is A[i] * (n - i). The optimal subset must be of this form for some i, so the answer is:
This is due to sorting. Use 64-bit arithmetic because the product can be up to .
I didn’t find an exact statement of this problem online; the closest I ran into were different “choose subset / maximize something” problems, but not this precise min·count objective. Those aren’t the same task, so I’m giving you a clean solution below. (GeeksforGeeks)
Fix a threshold . If you only choose stones with value , the minimum of the chosen set is at least . To maximize , for this you should include all stones , since adding more elements (that are still ) increases without decreasing the minimum below . Let be the count of elements ; then the best you can do at threshold is . It suffices to check equal to some array value, and sorting lets us compute each as A[i] * (n - i).
javaimport java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { FastScanner fs = new FastScanner(System.in); int n = fs.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = fs.nextLong(); Arrays.sort(a); // nondecreasing long best = Long.MIN_VALUE; // in case values can be negative for (int i = 0; i < n; i++) { long candidate = a[i] * (n - i); // use long to avoid overflow if (candidate > best) best = candidate; } System.out.println(best); } // Lightweight fast scanner static class FastScanner { private final InputStream in; private final byte[] buffer = new byte[1 << 16]; private int ptr = 0, len = 0; FastScanner(InputStream is) { in = is; } private int read() throws IOException { if (ptr >= len) { len = in.read(buffer); ptr = 0; if (len <= 0) return -1; } return buffer[ptr++]; } long nextLong() throws IOException { int c; do c = read(); while (c <= ' '); // skip space int sign = 1; if (c == '-') { sign = -1; c = read(); } long val = 0; while (c > ' ') { val = val * 10 + (c - '0'); c = read(); } return val * sign; } int nextInt() throws IOException { return (int) nextLong(); } } }
Notes
best to 0 instead; using Long.MIN_VALUE also safely covers negative inputs.