From ae267fed2313d43edd1a37d9651483d65df97053 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 10 Jun 2023 21:58:32 +0200 Subject: [PATCH] =?UTF-8?q?problems(cpp):=20add=20=E2=80=9C1802.=20Maximum?= =?UTF-8?q?=20Value=20at=20a=20Given=20Index=20in=20a=20Bounded=20Array?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...ue-at-a-given-index-in-a-bounded-array.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 problems/cpp/maximum-value-at-a-given-index-in-a-bounded-array.cpp diff --git a/problems/cpp/maximum-value-at-a-given-index-in-a-bounded-array.cpp b/problems/cpp/maximum-value-at-a-given-index-in-a-bounded-array.cpp new file mode 100644 index 0000000..f2c4cda --- /dev/null +++ b/problems/cpp/maximum-value-at-a-given-index-in-a-bounded-array.cpp @@ -0,0 +1,54 @@ +#include + +namespace { +long sum(long index, long value, long n) +{ + long count = 0; + + if (value > index) { + count += (2 * value - index) * (index + 1) / 2; + } else { + count += (value + 1) * value / 2 + index - value + 1; + } + + if (value >= n - index) { + count += (2 * value - n + 1 + index) * (n - index) / 2; + } else { + count += (value + 1) * value / 2 + n - index - value; + } + + return count - value; +} +} + +class Solution { +public: + int maxValue(int n, int index, int maxSum) + { + int left = 1, right = maxSum; + + while (left < right) { + int mid = (left + right + 1) / 2; + if (sum(index, mid, n) <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + + return left; + } +}; + +int main() +{ + Solution s; + + assert(s.maxValue(4, 2, 6) == 2); + assert(s.maxValue(6, 1, 10) == 3); + + // regression + assert(s.maxValue(6, 2, 931384943) == 155230825); + + return 0; +}