Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit04f95dd

Browse files
authored
Create 1425-constrained-subsequence-sum.kt
1 parentac77c60 commit04f95dd

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Time O(nlogn) and space O(n) using max heap
2+
classSolution {
3+
funconstrainedSubsetSum(nums:IntArray,k:Int):Int {
4+
var res= nums[0]
5+
val maxHeap=PriorityQueue<IntArray>() { a, b-> b[0]- a[0] }
6+
maxHeap.add(intArrayOf(nums[0],0))
7+
8+
for (iin1 until nums.size) {
9+
while (i- maxHeap.peek()[1]> k)
10+
maxHeap.poll()
11+
12+
var curMax= maxOf(nums[i], nums[i]+ maxHeap.peek()[0])
13+
res= maxOf(res, curMax)
14+
maxHeap.add(intArrayOf(curMax, i))
15+
}
16+
17+
return res
18+
}
19+
}
20+
21+
// Time O(n) and space O(n) using monotonic array/list
22+
classSolution {
23+
funconstrainedSubsetSum(nums:IntArray,k:Int):Int {
24+
var win=LinkedList<Int>()
25+
26+
var res=Integer.MIN_VALUE
27+
for (iin0 until nums.size) {
28+
nums[i]+= (win.peekFirst()?:0)
29+
res= maxOf(res, nums[i])
30+
31+
while (win.isNotEmpty()&& win.peekLast()< nums[i])
32+
win.removeLast()
33+
if (nums[i]>0)
34+
win.addLast(nums[i])
35+
if (i>= k&& win.isNotEmpty()&& win.peekFirst()== nums[i- k])
36+
win.removeFirst()
37+
}
38+
39+
return res
40+
}
41+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp