[LeetCode] Maximum Coin Collection

3466. Maximum Coin Collection

Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, lane1 and lane2, where the value at the ith index represents the number of coins he gains or loses in the ith mile in that lane.

  • If Mario is in lane 1 at mile i and lane1[i] > 0, Mario gains lane1[i] coins.
  • If Mario is in lane 1 at mile i and lane1[i] < 0, Mario pays a toll and loses abs(lane1[i]) coins.
  • The same rules apply for lane2.

Mario can enter the freeway anywhere and exit anytime after traveling at least one mile. Mario always enters the freeway on lane 1 but can switch lanes at most 2 times.

A lane switch is when Mario goes from lane 1 to lane 2 or vice versa.

Return the maximum number of coins Mario can earn after performing at most 2 lane switches.

Note: Mario can switch lanes immediately upon entering or just before exiting the freeway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
long long maxCoins(vector<int>& lane1, vector<int>& lane2) {
vector<vector<long long>> dp(2,vector<long long>(3,LLONG_MIN / 10));
dp[0][0] = 0;
long long res = LLONG_MIN;
for(int i = 0; i < lane1.size(); i++) {
long long l1 = lane1[i], l2 = lane2[i];

dp[0][2] = max(dp[0][2], dp[1][1]) + l1;
dp[1][1] = max({dp[1][1], 0ll, dp[0][0]}) + l2;
dp[0][0] = max(dp[0][0], 0ll) + l1;


res = max({res, dp[0][2], dp[0][0], dp[1][1]});
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/11/22/PS/LeetCode/maximum-coin-collection/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.