File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ using LL = long long ;
2+ class Solution {
3+ public:
4+ long long maximumCoins (vector<vector<int >>& coins, int k)
5+ {
6+ LL ret = 0 ;
7+ sort (coins.begin (), coins.end ());
8+ ret = max (ret, helper (coins, k));
9+
10+ for (auto & coin: coins)
11+ {
12+ int a = coin[0 ], b = coin[1 ];
13+ coin[0 ] = -b;
14+ coin[1 ] = -a;
15+ }
16+ sort (coins.begin (), coins.end ());
17+ ret = max (ret, helper (coins, k));
18+
19+ return ret;
20+ }
21+
22+ LL helper (vector<vector<int >>& coins, int k)
23+ {
24+ int n = coins.size ();
25+ int j = 0 ;
26+ LL sum = 0 ;
27+ LL ret = 0 ;
28+ for (int i=0 ; i<n; i++)
29+ {
30+ LL end = coins[i][0 ] + k -1 ;
31+ while (j<n && end >= coins[j][1 ])
32+ {
33+ sum += (LL)(coins[j][1 ]-coins[j][0 ]+1 )*coins[j][2 ];
34+ j++;
35+ }
36+ LL extra = 0 ;
37+ if (j<n && end >= coins[j][0 ])
38+ {
39+ extra += (LL)(end - coins[j][0 ] + 1 ) * coins[j][2 ];
40+ }
41+ ret = max (ret, sum + extra);
42+ sum -= (LL)(coins[i][1 ]-coins[i][0 ]+1 )*coins[i][2 ];
43+ }
44+ return ret;
45+ }
46+ };
You can’t perform that action at this time.
0 commit comments