Skip to content
Discussion options

You must be logged in to vote

We present a dynamic programming solution to count pairs of disjoint non-empty subsequences with equal GCD. Our approach tracks the number of ways to form two subsequences with specific GCD values simultaneously, processing each array element sequentially while deciding whether to skip it or assign it to either subsequence.

Approach

  • State Definition: Use dp[g1][g2] to store the number of ways to build two subsequences where the first has GCD g1 and the second has GCD g2
  • Base Case: Initialize dp[0][0] = 1 representing empty subsequences for both
  • Transition: For each element x in nums:
    • Skip the element (copy current dp state)
    • Add x to first subsequence: update GCD from g1 to gcd(g1, x)
    • Add x

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Jul 14, 2026
Collaborator

@mah-shamim
Comment options

mah-shamim Jul 14, 2026
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested hard Difficulty
2 participants