Skip to content

Commit 5fa5820

Browse files
authored
Create 2813-maximum-elegance-of-a-k-length-subsequence.js
1 parent bc4c51a commit 5fa5820

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {number[][]} items
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const findMaximumElegance = function (items, k) {
7+
let v = items
8+
let n = v.length
9+
const { max } = Math
10+
v.sort((a, b) => b[0] - a[0]) //sort according to profit
11+
let ans = 0
12+
let m = {}
13+
for (let i = 0; i < k; i++) {
14+
ans += v[i][0]
15+
if (m[v[i][1]] == null) m[v[i][1]] = 0
16+
m[v[i][1]]++
17+
}
18+
let sz = Object.keys(m).length
19+
ans += sz * sz
20+
let res = ans
21+
let j = k - 1
22+
for (let i = k; i < n; i++) {
23+
if (m[v[i][1]] == 0 || m[v[i][1]] == null) {
24+
//try to increase unique elements
25+
while (j >= 0 && m[v[j][1]] < 2) j-- //finding smallest number in 0 to k-1 whose frequency is more than 1, and removing it to increasing uniquenes of the subsequence
26+
if (j < 0) break //no number found that has frequency more than two
27+
m[v[j][1]]--
28+
m[v[i][1]]++
29+
res -= v[j][0]
30+
res += v[i][0]
31+
res -= sz * sz
32+
sz++
33+
res += sz * sz
34+
j--
35+
ans = max(ans, res) //keep taking max
36+
}
37+
}
38+
return max(ans, res)
39+
}

0 commit comments

Comments
 (0)