452. Longest Net Transaction Sequence
Asked in
Longest Net Transaction Sequence

A bank account has a sequence of money transactions. A positive amount represents money received, while a negative amount represents money sent.

Find the longest consecutive transaction sequence whose net amount is exactly targetNetAmount.

Return only the number of transactions in that sequence.

Class

TransactionAnalyzer

Method

longestNetSequence

public int longestNetSequence( List<Integer> transactionAmounts, int targetNetAmount)

  • transactionAmounts contains the transaction amounts in chronological order.
  • A positive amount represents money received.
  • A negative amount represents money sent.
  • targetNetAmount is the required net transaction amount.
  • Returns the maximum number of consecutive transactions whose sum equals targetNetAmount.
  • Returns 0 if no such sequence exists.

Rules

  • A sequence must contain one or more consecutive transactions.
  • Transaction amounts may be positive, negative, or zero.
  • The sum of the selected transaction amounts must equal targetNetAmount exactly.
  • Return only the sequence length.
  • The supplied transactionAmounts list must not be modified.

Constraints

  • 1 ≤ transactionAmounts.size() ≤ 200,000
  • -10,000 ≤ transactionAmounts.get(i) ≤ 10,000
  • -1,000,000,000 ≤ targetNetAmount ≤ 1,000,000,000
  • transactionAmounts and its elements are never null.

Examples

Example 1

longestNetSequence( transactionAmounts = List.of(500, -200, 300, -100, 400, -300, 200), targetNetAmount = 900)

Output: 5

The first five transactions have a net amount of 500 - 200 + 300 - 100 + 400 = 900.

Example 2

longestNetSequence( transactionAmounts = List.of(200, -500, 100, -200, 300, -100), targetNetAmount = -300)

Output: 4

The transactions -500, 100, -200, 300 have a net amount of -300.

Example 3

longestNetSequence( transactionAmounts = List.of(100, 200, -50), targetNetAmount = 1,000)

Output: 0

No consecutive transaction sequence has a net amount of 1,000.



Please use Laptop/Desktop or any other large screen to add/edit code.