Find all subarrays from a given array in the least possible time complexity.
Requirement:
calculate the square of (sum of even-indexed elements) - (the sum of odd-indexed elements) of al the subarrays.
Explanation of above code:
I am iterating the array, and inserting all elements of the subarray in the innerList. Then, summing up all the even-indexed and odd-indexed elements separately. Subtracting the even and odd sum, and calculating its square.
What I am looking for:
Optimization for the code.
My Solution:
public static void subarr2(int[] arr) {
int N = arr.length;
int set_size = (int) Math.pow(2, N);
List<List<Integer>> list = new ArrayList<>();
List<Integer> innerList = null;
int evnSum = 0, oddSum = 0, finalSum = 0;
Set<Integer> sums = new TreeSet<>(Comparator.reverseOrder());
for (int i = 1; i < set_size; i++) {
innerList = new ArrayList<>();
for (int j = 0; j < N - 1; j++) {
int temp = (int) (1 << j);
if ((i & temp) > 0) {
innerList.add(arr[j]);
}
}
innerList.add(arr[N - 1]);
if (innerList.size() > 1) {
list.add(innerList);
evnSum = oddSum = 0;
for (int m = 0; m < innerList.size(); m++) {
if (m % 2 == 0)
evnSum += innerList.get(m);
else
oddSum += innerList.get(m);
}
System.out.println("evnsum=" + evnSum + " subarr=" + innerList);
finalSum = Math.subtractExact(evnSum, oddSum);
sums.add((int) Math.pow(finalSum, 2));
}
}
System.out.println("Output=" + sums.stream().findFirst().get());
}
I want to know, if this code can be further optimized? or made more full proof to cover any corner-case scenarios?
Some of the test cases failed saying "Time limit exceeded > 4s".