From 25947df7bf317085bcf2d85e4bcd3b537eefba4a Mon Sep 17 00:00:00 2001 From: Xtha-Sunil Date: Wed, 30 Oct 2024 23:32:39 +0545 Subject: [PATCH] Added solution for find the number of ways to place people i. --- ...d-the-number-of-ways-to-place-people-i.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 C++/find-the-number-of-ways-to-place-people-i.cpp diff --git a/C++/find-the-number-of-ways-to-place-people-i.cpp b/C++/find-the-number-of-ways-to-place-people-i.cpp new file mode 100644 index 0000000..3b7b215 --- /dev/null +++ b/C++/find-the-number-of-ways-to-place-people-i.cpp @@ -0,0 +1,58 @@ +// Time: O(n^2) +// Space: O(1) + +// sort, array +class Solution { +public: + int numberOfPairs(vector>& points) { + sort(begin(points), end(points), [](const auto& a, const auto& b) { + return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1]; + }); + + int result = 0; + for (int i = 0; i < size(points); ++i) { + for (int j = i + 1, y = numeric_limits::min(); j < size(points); ++j) { + if (points[i][1] < points[j][1]) { + continue; + } + if (points[j][1] > y) { + y = points[j][1]; + ++result; + } + } + } + return result; + } +}; + +// Time: O(n^3) +// Space: O(1) +// sort, array +class Solution2 { +public: + int numberOfPairs(vector>& points) { + sort(begin(points), end(points), [](const auto& a, const auto& b) { + return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1]; + }); + + int result = 0; + for (int i = 0; i < size(points); ++i) { + for (int j = i + 1, y = numeric_limits::min(); j < size(points); ++j) { + if (points[i][1] < points[j][1]) { + continue; + } + bool valid = true; + for (int k = i + 1; k < j; ++k) { + if (points[i][1] >= points[k][1] && points[k][1] >= points[j][1]) { + valid = false; + break; + } + } + if (valid) { + ++result; + } + } + } + return result; + } +};