Similar Problems
Similar Problems not available
Find The Maximum Number Of Marked Indices - Leetcode Solution
Companies:
LeetCode: Find The Maximum Number Of Marked Indices Leetcode Solution
Difficulty: Medium
Topics: greedy binary-search two-pointers array sorting
Problem Statement:
You are given an array of integers nums of length n where all elements are unique. You need to maximize the number of indices i (0 <= i <= n - 1) such that nums[i] == i. The array index starts from zero.
Return the maximum number of such indices.
Example:
Input: nums = [4,2,0,1,3] Output: 3 Explanation: Out of the given array, nums[0] = 4, nums[1] = 2, nums[2] = 0, nums[3] = 1, nums[4] = 3. The maximum number of indices where nums[i] == i is 3. These indices are 2, 3, and 4.
Solution:
The problem can be solved by using a simple loop over the input array, and checking if the current element is equal to its index i.
Let's start by defining a function named "find_max_marked_indices" that takes in an array of integers "nums" as an input parameter. Inside the function, we would initialize a variable "max_marked_indices" to zero, which will keep track of the maximum number of indices where the element in the array is equal to its index.
Next, we would loop through the array and compare each element with its index. If the element is equal to its index, we would increase the "max_marked_indices" variable by one.
Finally, we would return the "max_marked_indices" as the result. Here's the Python code for this approach:
def find_max_marked_indices(nums: List[int]) -> int:
max_marked_indices = 0
for i in range(len(nums)):
if nums[i] == i:
max_marked_indices += 1
return max_marked_indices
The time complexity of this solution is O(n), where n is the length of the input array. Since we are iterating over the input array only once, this approach achieves the optimal time complexity.
Find The Maximum Number Of Marked Indices Solution Code
1