Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for 3202. Find the Maximum Length of Valid Subsequence II
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

3202. Find the Maximum Length of Valid Subsequence II

3202. Find the Maximum Length of Valid Subsequence II

Difficulty: Medium

Topics:Array,Dynamic Programming

You are given an integer arraynums and apositive integerk.

A subsequence1sub ofnums with lengthx is calledvalid if it satisfies:

  • (sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.

Returnthe length of thelongest valid subsequence ofnums.

Example 1:

  • Input: nums = [1,2,3,4,5], k = 2
  • Output: 5
  • Explanation: The longest valid subsequence is[1, 2, 3, 4, 5].

Example 2:

  • Input: nums = [1,4,2,3,1,4], k = 3
  • Output: 4
  • Explanation: The longest valid subsequence is[1, 4, 1, 4].

Constraints:

  • 2 <= nums.length <= 103
  • 1 <= nums[i] <= 107
  • 1 <= k <= 103

Hint:

  1. Fix the value of(subs[0] + subs[1]) % k from thek possible values. Let it beval.
  2. Letdp[i] store the maximum length of a subsequence with its last elementx such thatx % k == i.
  3. Answer for a subsequence ending at indexy isdp[(k + val - (y % k)) % k] + 1.

Solution:

We need to find the maximum length of a valid subsequence in an array where every consecutive pair of elements in the subsequence has the same modulo value when their sum is divided by a given integerk.

Approach

  1. Problem Analysis: The key observation is that for any valid subsequence, all consecutive pairs of elements must satisfy(a + b) % k = val for some fixed valueval. This condition implies that the residues of the elements in the subsequence must alternate between two residuesr0 andr1 such that(r0 + r1) % k = val. Additionally, the subsequence can consist of elements with a single residuer0 where(2 x r0) % k = val.

  2. Dynamic Programming Setup: For each possible valueval (from 0 tok-1), we use a dynamic programming arraydp wheredp[r] stores the maximum length of a valid subsequence ending with an element whose residue isr under the currentval.

  3. Processing Elements: For each element in the array, compute its residuer = num % k. The required residues for the previous element in the subsequence is given bys = (k + val - r) % k. The candidate length for the current element is either 1 (starting a new subsequence) ordp[s] + 1 (extending an existing subsequence ending with residues).

  4. Update DP State: Updatedp[r] to the maximum of its current value and the candidate length. Track the maximum subsequence length encountered across all residues and all values ofval.

  5. Result Extraction: After processing all elements for all possible values ofval, the maximum length found is the solution.

Let's implement this solution in PHP:3202. Find the Maximum Length of Valid Subsequence II

<?php/** * @param Integer[] $nums * @param Integer $k * @return Integer */functionmaximumLength($nums,$k){........./**     * go to ./solution.php     */}// Test cases// Example 1$nums1=[1,2,3,4,5];$k1=2;echo"Output: ".maximumLength($nums1,$k1)."\n";// Output: 5// Example 2$nums2=[1,4,2,3,1,4];$k2=3;echo"Output: ".maximumLength($nums2,$k2)."\n";// Output: 4?>
Enter fullscreen modeExit fullscreen mode

Explanation:

  1. Initialization: The algorithm initializes the maximum length$ans to 0.
  2. Iterate Over Values: For each possible valueval from 0 tok-1, it initializes a dynamic programming array$dp of sizek to store the maximum subsequence lengths ending with each residue.
  3. Process Elements: For each element in the array, it computes the residuer of the element modulok. The required previous residues is calculated as(k + val - r) % k.
  4. Update DP Array: The candidate length for the current element is set to 1 (if starting a new subsequence) or$dp[$s] + 1 (if extending an existing subsequence). The$dp array is updated if the candidate length exceeds the current value for residuer.
  5. Track Maximum Length: The maximum length encountered during the processing is stored in$ans.
  6. Return Result: After processing all elements and all values ofval, the algorithm returns the maximum valid subsequence length found.

This approach efficiently checks all possible valid subsequences by leveraging dynamic programming and modular arithmetic, ensuring optimal performance even for the upper constraint limits.

Contact Links

If you found this series helpful, please consider giving therepository a star on GitHub or sharing the post on your favorite social networks 😍.Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:


  1. Subsequence: Asubsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. 

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a Technical Lead with holistic knowledge of software development and design. I am also experienced in coordinating with stakeholders
  • Location
    2 NO MUSLIM NAGAR, MATUAIL, TUSHARDHARA, DEMRA - 1362, DHAKA, BANGLADESH
  • Education
    AHSANULLAH UNIVERSITY OF SCIENCE AND TECHNOLOGY
  • Pronouns
    he/him
  • Work
    TECH LEAD at MT TECHNOLOGIES
  • Joined

More fromMD ARIFUL HAQUE

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp