LeetCode-in-Java

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

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public long numberOfSubsequences(int[] nums) {
        Map<Double, Integer> freq = new HashMap<>();
        long ans = 0;
        for (int r = 4; r < nums.length; ++r) {
            for (int p = 0, q = r - 2; p < q - 1; ++p) {
                Double key = (double) nums[p] / nums[q];
                freq.put(key, freq.getOrDefault(key, 0) + 1);
            }
            for (int s = r + 2; s < nums.length; ++s) {
                ans += freq.getOrDefault((double) nums[s] / nums[r], 0);
            }
        }
        return ans;
    }
}