FastPrepGet Max Deletions

Get Max Deletions

JP Morgan Chase logoJP Morgan ChaseEasyINTERNOA
Learn

Problem statement

A control device has 4 buttons that can be used to move a character around a screen in 4 directions: Up (U), Down (D), Left (L), and Right (R). The movement needs to be optimized by deleting unnecessary instructions while maintaining the same destination. Given the original set of instructions, what is the maximum number of instructions that can be deleted and still have the character reach the destination?

Note: The instructions that are deleted do not need to be contiguous.

Function

getMaxDeletions(S: String) → int

Complete the function getMaxDeletions in the editor below.

getMaxDeletions has the following parameter:

  1. string S: the original instructions that were programmed

Returns int: the maximum number of instructions that can be deleted from S while maintaining the destination

Examples

Example 1

S = "URDR"return = 2
Example 1 illustration

Given an original set of instructions S = 'URDR', the final destination is 2 units to the right of the initial position after the character moves up, right, down, and right. If 'U' and 'D' are deleted, the destination remains the same. The answer 2 will be returned.

Example 2

S = "RRR"return = 0
Example 2 illustration

There is nothing that can be deleted from these instructions, so the answer is 0.

Constraints

  • 1 ≤ n ≤ 10^5
  • S contains only the characters 'U', 'D', 'L', and 'R'.

More JP Morgan Chase problems

See JP Morgan Chase hiring insights
public int getMaxDeletions(String S) {
  // write your code here
}
S"URDR"
expected2
Checking account…