-
Notifications
You must be signed in to change notification settings - Fork 0
/
deck_of_cards.cpp
128 lines (106 loc) · 2.78 KB
/
deck_of_cards.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
//
// deck_of_cards.cpp
// Algorithms Lab
//
// Created by Jonas Gessner
// Copyright © 2019 Jonas Gessner. All rights reserved.
//
#include <iostream>
#include <vector>
#include <climits>
int cards[100000];
using namespace std;
static void runTestCase()
{
int n;
cin >> n;
int k;
cin >> k;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
cards[i] = x;
}
int i = 0;
int j = 0;
int currentSum = cards[i];
int currentDistance = k - currentSum;
int closestAbsoluteDistance = INT_MAX;
int bestI = 0;
int bestJ = 0;
while (j < (n - 1) && closestAbsoluteDistance > 0 && currentDistance != 0)
{
bool brk = false;
while (j < (n - 1) && currentDistance > 0) // Diff is positive so we can add more elements
{
j++;
int addVal = cards[j];
if (addVal > k && addVal - k > closestAbsoluteDistance)
{
j++;
i = j;
currentSum = cards[i];
currentDistance = k - currentSum;
if (abs(currentDistance) < closestAbsoluteDistance)
{
closestAbsoluteDistance = abs(currentDistance);
bestI = i;
bestJ = j;
}
brk = true;
break;
}
currentSum += addVal;
currentDistance -= addVal;
if (abs(currentDistance) < closestAbsoluteDistance)
{
closestAbsoluteDistance = abs(currentDistance);
bestI = i;
bestJ = j;
}
}
if (brk)
{
continue;
}
while (currentDistance < 0 && i < j) // Diff is negative so we overshot. Remove elements from the left
{
int subVal = cards[i];
currentSum -= subVal;
currentDistance += subVal;
i++;
if (abs(currentDistance) < closestAbsoluteDistance)
{
closestAbsoluteDistance = abs(currentDistance);
bestI = i;
bestJ = j;
}
}
if (currentDistance < 0 && i == j)
{
i++;
j++;
currentSum = cards[i];
currentDistance = k - currentSum;
if (abs(currentDistance) < closestAbsoluteDistance)
{
closestAbsoluteDistance = abs(currentDistance);
bestI = i;
bestJ = j;
}
}
}
cout << bestI << " " << bestJ << "\n";
}
int main(int argc, const char *argv[])
{
ios_base::sync_with_stdio(false);
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
runTestCase();
}
return 0;
}