The minimum number of elements to reach the end of an array

本文介绍了一种算法,该算法用于找出在给定数组中从起始位置到达末尾所需的最少元素选择次数。每个数组元素代表可以向前跳跃的最大步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers, each element represents the max number of jumps that you can move forward.
Write a piece of code to find out the minimum number of elements you need to select to reach the end of the array (starting from the first element).
• All integers is equal to or greater than 0
• If an element is 0, you cannot make any jumps
• -1 should be output if it is unable to reach the end of the array
Here is an example to illustrate the question.
Sample Input: 1,3,5,2,9,3,1,1,8
Sample Output: 3
Explanation:
Here the min # of selections is : 3
with the sequence : 1-> 3 -> 9 ->8
First element is 1, so can only go to 3.

Second element is 3, so can make at most 3 jumps: eg to 5 or 2 or 9.

Another example:
Input: 1, 0
Ouput: -1
Explanation: the first element is 1, so can only go to 0. Then can not make any jumps, so we can not reach the end of the array.


#include <iostream>
using namespace std;

int walk(int *arr, int len);

int walk(int *arr, int len)
{
	if (len <=0)
	{
		return 0;
	}
	if(*arr <= 0)
	{	
		return -1;
	}
	//print the element indicating the max steps we can take
	cout<<*arr<<" ";
	//we can reach the end of array by this element
	if(len == 1 || *arr > len-1)
	{
		return 1;
	}
	int max_step = *arr;
	//this array has at least two elements
	//we suppose the nearest element can proceed further
	int *pos = arr+1;
	int *p;
	for (p = arr+2; p<=arr+max_step; p++)
	{
		//if the next element can proceed further, then mark the position.
		if (*p > *pos-(p-pos))
		{
			pos = p;
		}
	}
	int steps = walk(pos, len-(pos-arr));
	if (steps == -1)
	{
		return -1;//we can never reach the end
	}
	else
	{
		return 1+steps;//increment the steps
	}
}


int main()
{
	int arr[] = {1,3,5,2,4,3,1,2,0,0};
	int steps = walk(arr, sizeof(arr)/sizeof(int));
	cout<<endl<<"the steps:"<<steps<<endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值