LeetCode in Kotlin

3404. Count Special Subsequences

Medium

You are given an array nums consisting of positive integers.

A special subsequence is defined as a subsequence of length 4, represented by indices (p, q, r, s), where p < q < r < s. This subsequence must satisfy the following conditions:

A subsequence is a sequence derived from the array by deleting zero or more elements without changing the order of the remaining elements.

Return the number of different special subsequences in nums.

Example 1:

Input: nums = [1,2,3,4,3,6,1]

Output: 1

Explanation:

There is one special subsequence in nums.

Example 2:

Input: nums = [3,4,3,4,3,4,3,4]

Output: 3

Explanation:

There are three special subsequences in nums.

Constraints:

Solution

class Solution {
    fun numberOfSubsequences(nums: IntArray): Long {
        val freq: MutableMap<Double, Int> = HashMap()
        var ans: Long = 0
        for (r in 4..<nums.size) {
            var p = 0
            val q = r - 2
            while (p < q - 1) {
                val key = nums[p].toDouble() / nums[q]
                freq.put(key, freq.getOrDefault(key, 0) + 1)
                ++p
            }
            for (s in r + 2..<nums.size) {
                ans += freq.getOrDefault(nums[s].toDouble() / nums[r], 0).toLong()
            }
        }
        return ans
    }
}