leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 090091712aea5abfb0b7dfc17db3a00e6fc131b5
parent 308a71e413c0fabf54727efaf5befc77d72fb362
Author: Jack Sangdahl <jack@pngu.org>
Date:   Wed, 31 Dec 2025 21:51:37 -0700

1521. find a value of a mysterious function closest to target

Diffstat:
Afind_val_mysterious_func_target.c | 27+++++++++++++++++++++++++++
Afind_val_mysterious_func_target.py | 30++++++++++++++++++++++++++++++
2 files changed, 57 insertions(+), 0 deletions(-)

diff --git a/find_val_mysterious_func_target.c b/find_val_mysterious_func_target.c @@ -0,0 +1,27 @@ +// 1521. Find a Value of a Mysterious Function Closest to Target +#include "leetcode.h" + +/* + * winston was given the above mysterious function 'func'. he has an integer + * array 'arr' and an integer 'target' and he wants to find the values 'r' and + * 'l' that make the value '|func(arr, l, r) - target|' minimum possible. return + * the minimum possible value of '|func(arr, l, r) - target|'. notice that + * 'func' should be called with vaues 'l' and 'r' where '0 <= l, r < + * arr.length'. + */ + +int closestToTarget(int *arr, int arrSize, int target) { + int ans = INT_MAX; + for (int i = 0; i < arrSize; i++) { + ans = fmin(ans, abs(arr[i] - target)); + for (int j = i - 1; j >= 0 && (arr[j] & arr[i]) != arr[j]; --j) + ans = fmin(ans, abs((arr[j] &= arr[i]) - target)); + } + return ans; +} + +int main() { + int a1[] = {9, 12, 3, 7, 15}, a2[] = {1000000, 1000000, 1000000}; + printf("%d\n", closestToTarget(a1, ARRAY_SIZE(a1), 5)); // expect: 2 + printf("%d\n", closestToTarget(a2, ARRAY_SIZE(a2), 1)); // expect: 999999 +} diff --git a/find_val_mysterious_func_target.py b/find_val_mysterious_func_target.py @@ -0,0 +1,30 @@ +# 1521. Find a Value of a Mysterious Function Closest to Target + +""" +winston was given the above mysterious function 'func'. he has an integer +array 'arr' and an integer 'target' and he wants to find the values 'r' and +'l' that make the value '|func(arr, l, r) - target|' minimum possible. return +the minimum possible value of '|func(arr, l, r) - target|'. notice that +'func' should be called with vaues 'l' and 'r' where '0 <= l, r < +arr.length'. +""" + + +class Solution(object): + def closestToTarget(self, arr, target): + """ + :type arr: List[int] + :type target: int + :rtype: int + """ + ans, curr = float("inf"), set() + for i in arr: + curr = {j & i for j in curr} | {i} + ans = min(ans, min(abs(j - target) for j in curr)) + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.closestToTarget(arr=[9, 12, 3, 7, 15], target=5)) + print(obj.closestToTarget(arr=[1000000, 1000000, 1000000], target=1))