精華區beta Marginalman 關於我們 聯絡資訊
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
pandix: 大師 05/24 16:23
MurasakiSion: 大師 05/24 16:23
Che31128: 大師 05/24 16:27
pandix: 我的話會用每個nums2[i]當成最小值的情況下 最佳解會是多 05/24 16:34
pandix: 少來解釋 05/24 16:34
NTHUlagka: 同上 p大的那種思路感覺會比較好想 05/24 17:25
NTHUlagka: 大師 05/24 18:24
ekids1234: 看了解法之後頭好痛 估狗了一下竟然搜到這邊 = = 05/24 22:44
ekids1234: 開啟 bbs 連進這個版 按好幾個上還不見這串Y 05/24 22:45
ekids1234: 這個版廢文也太多了吧 = = 05/24 22:45
ekids1234: 這題真的搞死我 sort 和 pq 一下升序一下降序 05/24 22:46
ekids1234: 然後又得維護 pq 長度 前後又出了兩個 bug 05/24 22:47
ekids1234: 只為了看那個火點起來 ..... 05/24 22:47
ekids1234: 但最苦的還是 面是考的話這我哪想的到 05/24 22:49