Ctrl K

Hops With a Parity Toll

Medium
You start at position 0 of the array values and only move forward: from position i you may jump to any position j > i, skipping as many elements as you like. Every position you visit (including the starting one) earns you values[i] points. However, each jump between numbers of different parity costs you penalty points. You may stop anywhere. Return the highest score you can achieve.
Example 1
values=[4, 7, 10, 3, 8], penalty=4 → 22

Stay on the even numbers: 4 → 10 → 8 gives 22. Picking up 7 and 3 as well forces several parity changes, each costing 4, and the total ends up lower.

Example 2
values=[2, 9, 11, 13], penalty=1 → 34

A single parity change costs only 1: 2 + 9 + 11 + 13 - 1 = 34.

Example 3
values=[5, 1], penalty=100 → 6
Constraints
  • 2 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁶
  • 1 ≤ penalty ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
values=[4, 7, 10, 3, 8], penalty=4
Expected
22

Run checks the first 3 tests in your browser. Submit checks all 109 tests on the server, hidden ones included.