What will be the output of the following code?
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int n)
{
int count[n];
memset(count, 0, sizeof(count));
for (int i=n-2; i>=0; i--)
{
if (arr[i] >= n - i - 1)
count[i]++;
for (int j=i+1; j < n-1 && j <= arr[i] + i; j++)
if (count[j] != -1)
count[i] += count[j];
if (count[i] == 0)
count[i] = -1;
}
for (int i=0; i<n; i++)
cout << count[i] << " ";
}
int main()
{
int arr[] = {1, 3, 5, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, n);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int n)
{
int count[n];
memset(count, 0, sizeof(count));
for (int i=n-2; i>=0; i--)
{
if (arr[i] >= n - i - 1)
count[i]++;
for (int j=i+1; j < n-1 && j <= arr[i] + i; j++)
if (count[j] != -1)
count[i] += count[j];
if (count[i] == 0)
count[i] = -1;
}
for (int i=0; i<n; i++)
cout << count[i] << " ";
}
int main()
{
int arr[] = {1, 3, 5, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, n);
return 0;
}A. 3
B. 4
C. 4 4 2 1 0
D. 4 2 2 0 1
Answer: Option C
Related Questions on Arrays in Data Structures
What is the time complexity of accessing an element in an array by index?
A. O(n)
B. O(1)
C. O(log n)
D. O(n log n)
Which of the following is the correct way to declare an array in C?
A. int array[];
B. array{int};
C. int array[10];
D. int array();
How do you find the length of an array in Java?
A. array.size();
B. array.length;
C. array.length();
D. array.size;

Join The Discussion