From ad97eee4caf9ee957166810a052d1632f7221026 Mon Sep 17 00:00:00 2001 From: iagorrr Date: Wed, 21 Aug 2024 16:28:26 -0300 Subject: [PATCH] improve: now min & max check returns an std::optional --- content/Extras/Max & min check.cpp | 35 ++++++++++++++---------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/content/Extras/Max & min check.cpp b/content/Extras/Max & min check.cpp index 87091ccf..cd851845 100644 --- a/content/Extras/Max & min check.cpp +++ b/content/Extras/Max & min check.cpp @@ -1,42 +1,39 @@ /*8< - @Title: + @Title: Max \& Min Check - Max \& Min Check + @Description: Returns the min/max value in range + [l, r] that satisfies the lambda function check, + if there is no such value the 'nullopt' is + returned. - @Description: + @Usage: check must be a function that receives + an integer and return a boolean. - Returns the min/max value in range [l, r] that - satisfies the lambda function check, if there - is no such value the max/min possible value - for that type will be returned. - - @Time: - - $O(\log{l-r+1})$ + @Time: $O(\log{l-r+1})$ >8*/ template -T maxCheck(T l, T r, function check) { - T best = numeric_limits::min(); +optional maxCheck(T l, T r, auto check) { + optional ret; while (l <= r) { T m = midpoint(l, r); if (check(m)) - chmax(best, m), l = m + 1; + ret ? chmax(ret, m) : ret = m, l = m + 1; else r = m - 1; } - return best; + return ret; } template -T minCheck(T l, T r, function check) { - T best = numeric_limits::max(); +optional minCheck(T l, T r, auto check) { + optional ret; while (l <= r) { T m = midpoint(l, r); if (check(m)) - chmin(best, m), r = m - 1; + ret ? chmin(ret, m) : ret = m, r = m - 1; else l = m + 1; } - return best; + return ret; }