Hello, everyone preparing for coding tests! Today, we will conduct the second lecture on ‘Finding Minimum Value’. In this lecture, we will address an algorithm problem that requires finding the minimum value in a given array that satisfies a specific condition. I will explain the process of solving this algorithm problem step by step, so please read carefully.
Problem Description
Given an integer array nums
and an integer target
, write a function that returns the minimum value among numbers in the array that are less than target
. If no such number exists, it should return -1.
Example Input and Output
- Input:
nums = [1, 3, 5, 7, 9]
,target = 6
- Output:
5
- Input:
nums = [1, 2, 3]
,target = 1
- Output:
-1
Approach to the Problem
To solve this problem, you need to follow these steps:
- Traverse the array to find numbers less than
target
. - Store the minimum value among the found numbers.
- If there are no numbers that satisfy the condition, return -1; otherwise, return the minimum value.
Algorithm Analysis
The time complexity to solve the above problem is O(n) because the array is traversed only once. The space complexity is O(1) as no additional space is required.
Code Implementation
Now, let’s write Python code based on the above algorithm.
def find_min_less_than_target(nums, target):
min_value = float('inf') # Initialize to infinity
found = False # Variable to check if a number satisfying the condition has been found
for num in nums:
if num < target:
found = True # Found a number less than target
min_value = min(min_value, num) # Update minimum value
return min_value if found else -1 # Return value based on condition satisfaction
Test Cases
After writing the code, you should check if it works correctly with a few test cases.
assert find_min_less_than_target([1, 3, 5, 7, 9], 6) == 5
assert find_min_less_than_target([1, 2, 3], 1) == -1
assert find_min_less_than_target([10, 15, 20, 25, 30], 20) == 15
assert find_min_less_than_target([1, 2, 3, 0, -1], 2) == 1
assert find_min_less_than_target([], 5) == -1
Conclusion
In this lecture, we solved the problem of finding the minimum value in an array that satisfies a specific condition. Through the implementation of the algorithm and performance analysis, we learned how to clearly understand and solve the problem. I hope you continue to challenge various algorithm problems to build your skills. We will return with another topic next time. Thank you!