LeetCode 3290: Maximum Multiplication Score
Problem Description
Explanation:
To solve this problem, we need to choose 4 indices from array b
such that they are in increasing order and then calculate the score based on the given formula. We can achieve the maximum score by choosing the elements from b
that have the highest positive or negative values.
To solve this problem efficiently, we can follow these steps:
- Sort the array
a
in non-decreasing order. - Sort the array
b
in non-increasing order. - Initialize the maximum score as Integer.MIN_VALUE.
- Iterate over all possible combinations of indices
i0
,i1
,i2
, andi3
in arrayb
. - Calculate the score using the given formula and update the maximum score if the calculated score is greater.
- Return the maximum score.
Time Complexity:
The time complexity of this approach is O(n^4), where n is the size of array b
.
Space Complexity:
The space complexity is O(1) as we are using constant extra space.
:
Solutions
class Solution {
public int maxScore(int[] a, int[] b) {
Arrays.sort(a);
Arrays.sort(b);
int maxScore = Integer.MIN_VALUE;
for (int i = 0; i < b.length - 3; i++) {
for (int j = i + 1; j < b.length - 2; j++) {
for (int k = j + 1; k < b.length - 1; k++) {
for (int l = k + 1; l < b.length; l++) {
int score = a[0] * b[i] + a[1] * b[j] + a[2] * b[k] + a[3] * b[l];
maxScore = Math.max(maxScore, score);
}
}
}
}
return maxScore;
}
}
Loading editor...