call(back)
Algorithms & Data StructuresmediumSign in to star problems

Longest Stable Transaction Period

Each day's net transaction value is recorded in transactions. A period of consecutive days is stable when the sum of its values is divisible by the stability factor k. Return the length of the longest stable period, or 0 if there is none.

transactions = [2, 3, 1, 4, 1, 5, 9], k = 3  ->  4   // days 2..5: 3 + 1 + 4 + 1 = 9
transactions = [1, 1], k = 3                 ->  0
transactions = [-3, 6, 2], k = 3             ->  2   // -3 + 6 = 3

Values may be negative; k >= 1.

Hints

Hint 1

A period i..j is divisible by k exactly when the prefix sums before i and after j have the same remainder modulo k.

Hint 2

Record the first index at which each remainder appears (remainder 0 appears at index 0, before any day). The longest period ending at j reaches back to that first index.

Hint 3

JavaScript's % keeps the sign of the dividend; normalise with ((x % k) + k) % k so negative sums land in 0..k-1.

Topics

Asked at

Similar Problems6