当前位置:网站首页>Algorithm -- find and maximum length k subsequence (kotlin)

Algorithm -- find and maximum length k subsequence (kotlin)

2022-06-24 09:37:00 Xiaomi technology Android R & D caoxinyu

subject

Input :nums = [-1,-2,3,4], k = 3
Output :[-1,3,4]
explain :
Subsequences have maximum sum :-1 + 3 + 4 = 6 .
Example 3:

Input :nums = [3,4,3,3], k = 2
Output :[3,4]
explain :
Subsequences have maximum sum :3 + 4 = 7 .
Another feasible subsequence is [4, 3] .

Tips :

1 <= nums.length <= 1000
-105 <= nums[i] <= 105
1 <= k <= nums.length

source : Power button (LeetCode)
link :https://leetcode.cn/problems/find-subsequence-of-length-k-with-the-largest-sum
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

resolvent

    fun maxSubsequence(nums: IntArray, k: Int): IntArray {
    
        var pair = Array(nums.size) {
     Array(2) {
     0 } }
        nums.forEachIndexed {
     index, i ->
            run {
    
                pair[index][0] = nums[index]
                pair[index][1] = index
            }
        }
        Arrays.sort(pair,0,pair.size) {
     o1, o2 -> if (o1[0] > o2[0]) -1 else 1 }

        Arrays.sort(pair,0,k) {
     o1, o2 -> if (o1[1] > o2[1]) 1 else -1 }
        var result = IntArray(k)
        for (i in 0 until k){
    
            result[i] = pair[i][0]
        }
        return result
    }

summary

1. This question uses map Don't fit , Because there are duplicate numbers , But you can use two-dimensional arrays to assist
2. Don't underestimate this question , At that time, I read the solution of the problem and worked it out in a limited time

原网站

版权声明
本文为[Xiaomi technology Android R & D caoxinyu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240821082474.html