![](/img/trans.png)
[英]Given an array and a sum, find the max length continous subarray less than the sum
[英]calculate the max length of an array such that average is less than given value
我一直在試圖解決這個問題,但大多數測試用例都超時了。 誰能幫我優化一下?
問題陳述 :
給定一個長度為 N 的數組 A。你必須從給定的數組 A 中選擇一個子集 S,使得 S 的平均值小於 K。你需要打印 S 的最大可能長度。
輸入格式:
The first line of each input contains N, length of array A.
Next line contains N space separated elements of array A.
Next line of input contains an integer Q, Number of queries.
Each following Q lines contains a single integer K.
輸出格式 :
For each query, print single integer denoting the maximum possible length of the subset.
樣本輸入
5 1 2 3 4 5 5 1 2 3 4 5
樣本輸出
0 2 4 5 5
解釋
這是我的解決方案:
import java.util.*;
public class Playground {
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
long n = Long.parseLong(s.nextLine()); // Reading input from STDIN
String[] temp = s.nextLine().trim().split(" ");
long[] arr = new long[(int) n];
for (int i = 0; i < n; i++)
arr[i] = Integer.parseInt(temp[i]);
long q = Long.parseLong(s.nextLine());
long[] queries = new long[(int) q];
for (int i = 0; i < q; i++) {
long x = Long.parseLong(s.nextLine());
queries[i] = x;
}
PriorityQueue<Long> queue = new PriorityQueue<>();
for (long x : arr)
queue.add(x);
for (long x : queries) {
double avg = 0;
List<Long> list = new ArrayList<>();
int i = 0;
int sum = 0;
boolean flag = false;
while (! queue.isEmpty()) {
long num = queue.poll();
i++;
list.add(num);
sum += num;
avg = (double) sum / i;
if (avg >= x) {
System.out.println(i - 1);
flag = true;
break;
}
}
if (! flag)
System.out.println(n);
queue.addAll(list);
}
}
}
解決這個問題的一個簡單方法是先對數組進行排序。
在對數組進行排序后,每個元素都等於或大於最后一個元素,然后求解單次運行就很容易了:
int count = 0;
int limit = 0;
for (int i : sortedArray) {
int diff = i - maxAvg;
if (limit + diff < 0) {
limit += diff;
count++
} else {
break;
}
}
System.out.println(count);
這是有效的,因為如果與最大平均值的差異為負,您可以使用具有正差異的值,直到達到限制。
對數組進行排序是O(n*log(n))
,對於每個解決方案,您只需要O(n)
這是我所有解析的完整解決方案:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arrLen = Integer.parseInt(sc.nextLine());
int[] array = new int[arrLen];
String[] strNums = sc.nextLine().split(" ", arrLen);
for (int i = 0; i < arrLen; i++) {
array[i] = Integer.parseInt(strNums[i]);
}
Arrays.sort(array);
int numTests = Integer.parseInt(sc.nextLine());
for (int i = 0; i < numTests; i++) {
int maxAvg = Integer.parseInt(sc.nextLine());
int limit = 0;
int count = 0;
for (int j : array) {
int diff = j - maxAvg;
if (limit + diff < 0) {
count++;
limit += diff;
} else {
break;
}
}
System.out.println(count);
}
sc.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.