Re: [閒聊] 每日LeetCode
https://leetcode.com/problems/maximum-subsequence-score/description/
2542. Maximum Subsequence Score
給你兩個大小一樣的陣列 nums1 和 nums2,以及一個數字 k,找出大小為 k 的子序列,
透過下列規則計算出分數 score:
score = (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) *
min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1])
求出 score 最大是多少。
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.
思路:
1.最大分數需要 nums1 的和越高越好,nums2 的最小數越大越好,兩者相乘才會最高,簡
單講就是要求長度為k的最優Pair。
2.我們可以先讓Pair的其中一邊是最佳解,再嘗試把其他nums1的元素加進來比較,如果得
到更大分數,就把比較小的鍵值對移除得到更優解。
3.因為分數是 nums2 的「其中一個數字」乘以nums1的「多個數字之和」,所以nums2變化
比較小,我們把nums2由大到小排序並取k個Pair可以得到一個局部最佳解ans。
4.從k+1位置開始,每次嘗試加入一個新Pair,如果加入後的和變更大就把序列裡的最小
值移除加入新的Pair,並計算nums2次優和nums1更優解相乘是否更大,更新ans。
5.把nums1的序列放進一個MinHeap,這樣如果和更大,每次pop出來的都是最小元素。
Java Code:
-------------------------------------------------
class Solution {
public long maxScore(int[] nums1, int[] nums2, int k) {
// 記錄nums2排序後的索引
int n = nums1.length;
Integer[] indices = new Integer[n];
for (int i = 0; i < n; i++) {
indices[i] = i;
}
Arrays.sort(indices, (a, b) -> nums2[b] - nums2[a]);
// 把k個nums2最優解的元素加入序列
PriorityQueue<Integer> heap = new PriorityQueue<>();
long sum = 0;
for (int i = 0; i < k; i++) {
int index = indices[i];
heap.offer(nums1[index]);
sum += (nums1[index]);
}
// nums2最優解
long ans = sum * nums2[indices[k - 1]];
// 嘗試讓nums1變成更優解並更新解答
for (int i = k; i < n; i++) {
int index = indices[i];
int val = nums1[index];
if (val > heap.peek()) {
sum += val - heap.poll();
heap.offer(val);
ans = Math.max(ans, sum * nums2[index]);
}
}
return ans;
}
}
-------------------------------------------------
今天這題不好講也不好寫 = =
--
https://i.imgur.com/PIoxddO.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1684916455.A.5F4.html
推
05/24 16:23,
1年前
, 1F
05/24 16:23, 1F
推
05/24 16:23,
1年前
, 2F
05/24 16:23, 2F
推
05/24 16:27,
1年前
, 3F
05/24 16:27, 3F
推
05/24 16:34,
1年前
, 4F
05/24 16:34, 4F
→
05/24 16:34,
1年前
, 5F
05/24 16:34, 5F
推
05/24 17:25,
1年前
, 6F
05/24 17:25, 6F
推
05/24 18:24,
1年前
, 7F
05/24 18:24, 7F
推
05/24 22:44,
1年前
, 8F
05/24 22:44, 8F
→
05/24 22:45,
1年前
, 9F
05/24 22:45, 9F
→
05/24 22:45,
1年前
, 10F
05/24 22:45, 10F
→
05/24 22:46,
1年前
, 11F
05/24 22:46, 11F
→
05/24 22:47,
1年前
, 12F
05/24 22:47, 12F
→
05/24 22:47,
1年前
, 13F
05/24 22:47, 13F
→
05/24 22:49,
1年前
, 14F
05/24 22:49, 14F
討論串 (同標題文章)
完整討論串 (本文為第 329 之 719 篇):
閒聊
1
3