Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

java - Total number of ways such that the sum of elements is less than or equal to k

Task: Find the number of possible ways to pick a single element from each array, such that their sum is less than k.

Here is my program looks like:

public static long process(List<Integer> a, List<Integer> b, List<Integer> c, List<Integer> d, int k) {
    Collections.sort(a);
    Collections.sort(b);
    Collections.sort(c);
    Collections.sort(d);
    long total = 0;
    // four layer for loop to check all combinations of four arrays
    for (int i = 0; i < a.size(); i++) {
        long v = a.get(i);
        for (int j = 0; j < b.size() && v < k; j++) {
            long v1 = b.get(j);
            for (int m = 0; m < c.size() && v + v1 < k; m++) {
                long v2 = c.get(m);
                for (int l = 0; l < d.size() && v + v1 + v2 < k; l++) {
                    long v3 = d.get(l);
                    if (v + v1 + v2 + v3 <= k) {
                        total = total + 1;
                    } else {
                        break;
                    }
                }
            }
        }
    }
    return total;   
}

This was asked during an interview, I see that when I have used it, the program failed for test cases saying time limit exceeded.

What is best approach to follow for this task?

question from:https://stackoverflow.com/questions/66062522/total-number-of-ways-such-that-the-sum-of-elements-is-less-than-or-equal-to-k

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let the length of the lists be N. Your approach is O(N^4), which is likely to time out.
A simple yet faster approach would be:

  1. Generate all pair sums (which are less than k) from arrays A and B. Store them in an array X. Complexity: O(N^2)
  2. Generate all pair sums (which are less than k) from arrays C and D, store them in array Y. Complexity: O(N^2)
  3. Sort arrays X and Y. Complexity: O(N^2 logN)
  4. For each element in X, find the maximum element in Y such that their sum < k. Using binary search, complexity: O(N^2 logN)

Space complexity: O(N^2), Time Complexity: O(N^2 logN)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...