-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMax_Subsequence_Score.java
More file actions
52 lines (41 loc) · 2.01 KB
/
Max_Subsequence_Score.java
File metadata and controls
52 lines (41 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k. You must choose a subsequence of indices from nums1 of length k.
// For chosen indices i0, i1, ..., ik - 1, your score is defined as:
// The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2.
// It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1]).
// Return the maximum possible score.
// A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements.
// Example 1:
// Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
// Output: 12
// Explanation:
// The four possible subsequence scores are:
// - We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
// - We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
// - We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
// - We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
// Therefore, we return the max score, which is 12.
// Example 2:
// Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
// Output: 30
// Explanation:
// Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
class Solution {
public long maxScore(int[] nums1, int[] nums2, int k) {
int n = nums1.length;
int maxScore = Integer.MIN_VALUE;
for(int i=0;i<=k;i++){
int[] nums1copy = nums1.clone();
int[] nums2copy = nums2.clone();
Arrays.sort(nums1copy);
Arrays.sort(nums2copy);
int score = 0;
int minNums2 = Integer.MAX_VALUE;
for(int j=0;j<i;j++){
score += nums1copy[n - k + j];
minNums2 = Math.min(minNums2, nums2copy[j]);
}
maxScore = Math.max(maxScore, score * minNums2);
}
return maxScore;
}
}