Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion contest/src/main/java/com/github/contest/Execute.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.github.contest


import com.github.contest.hashTable.countGoodAlternativeSolution
import com.github.contest.math.numberOfPowerfulInt
import com.github.contest.strings.fullJustify
import com.github.contest.strings.subStrHash
Expand All @@ -13,6 +14,11 @@ import java.util.TreeMap

fun main() {

countGoodAlternativeSolution(intArrayOf(3, 1, 4, 3, 2, 2, 4), 2).also { println(it) }

}

fun fullJustifyData() {
fullJustify(
arrayOf(
"Science",
Expand All @@ -39,7 +45,6 @@ fun main() {
it
)
}

}

fun subStrHashData() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,43 @@ fun countBadPairsAltSolution(nums: IntArray): Long {

class Counter {
var count: Int = 0
}

/**
* 2537. Count the Number of Good Subarrays
* Alternative Solution Optimal
* Hash Map Approach
*/

fun countGoodAlternativeSolution(nums: IntArray, k: Int): Long {
var left = 0
var count = 0L
var totalPairs = 0L
val freq = mutableMapOf<Int, Int>()

for (right in nums.indices) {

val num = nums[right]
val currentFreq = freq.getOrDefault(num, 0)

totalPairs += currentFreq
freq[num] = currentFreq + 1


while (totalPairs >= k) {
val leftNum = nums[left]

totalPairs -= freq[leftNum]!! - 1
freq[leftNum] = freq[leftNum]!! - 1
if (freq[leftNum] == 0) {
freq.remove(leftNum)
}
left++
}


count += left
}

return count
}
Original file line number Diff line number Diff line change
Expand Up @@ -331,4 +331,38 @@ fun isAnagram(s: String, t: String): Boolean {
}

return true
}

/**
* 2537. Count the Number of Good Subarrays
* TLE Approach
*/

fun countGood(nums: IntArray, k: Int): Long {
if (nums.hasSingle()) return 0L

var count = 0L
var left = 0

while (left < nums.size) {
var right = left + 1
while (right < nums.size) {
var localCounter = 0
for (i in left..right) {
for (j in i + 1..right) {
if (nums[i] == nums[j]) localCounter++
}
}
if (localCounter >= k) count++
right++
}
left++
}

return count
}

private fun IntArray.hasSingle() = when {
this.size == 1 -> true
else -> false
}