From b8aa81f856a5e401cb6ab6c49efaaa9dff9e05a9 Mon Sep 17 00:00:00 2001 From: Deepak Date: Fri, 27 Oct 2023 22:30:29 +0530 Subject: [PATCH] Create jump _greedy-problem.py fixes #4692 --- .../maths/jump _greedy-problem.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/java/com/thealgorithms/maths/jump _greedy-problem.py diff --git a/src/main/java/com/thealgorithms/maths/jump _greedy-problem.py b/src/main/java/com/thealgorithms/maths/jump _greedy-problem.py new file mode 100644 index 000000000000..cc9becf953d1 --- /dev/null +++ b/src/main/java/com/thealgorithms/maths/jump _greedy-problem.py @@ -0,0 +1,28 @@ +def can_reach_last_index_optimized(nums): + """ + Determines whether the last index of an integer array can be reached by jumping from the first index, + where each element in the array represents the maximum jump length at that position. + + Args: + nums: A list of integers. + + Returns: + A boolean value, True if the last index can be reached, False otherwise. + """ + + # Initialize the current index and maximum reachable index. + current_index = 0 + max_reachable_index = nums[0] + + # Loop until we reach the last index or we cannot jump any further. + while current_index < len(nums) - 1: + # If the maximum reachable index is not enough to reach the last index, return false. + if max_reachable_index < len(nums) - 1: + return False + + # Update the current index and maximum reachable index. + current_index += 1 + max_reachable_index = max(max_reachable_index, nums[current_index] + current_index) + + # If we reach this point, we can reach the last index. Return true. + return True