Loop array to find subscript

Given an array A1, A2,… AN containing N integers, you can choose any Ai and rotate Ai to the first item of the array, that is, the array becomes:

Ai, Ai + 1, Ai + 2,… AN, A1, A2,…, Ai-1

Now Xiao Hi hopes that the rotated array satisfies:

For any K (1 ≤ i ≤ N), the sum of the previous K terms is positive.

For example, for A=[3, -5, 2, -2, 3, 0], the rotation to [3, 0, 3, -5, 2, -2] satisfies the condition.

Please output i, which means turning Ai to the first item meets the condition.

If there are multiple solutions, you can output any i. If there is no solution, output -1.

The
first line of Input contains an integer N.

The second line contains N integers A1, A2,… AN.

For 50% of the data, 1 ≤ N ≤ 1000

For 100% data, 1 ≤ N ≤ 100000, -1000000 ≤ Ai ≤ 1000000

Output
an integer represents the answer.

Sample Input
6
3 -5 2 -2 3 0
Sample Output
5

The meaning of the question is not difficult to understand, this question is not difficult to write, violence can also be passed, I have never done it because my array is too small, really damn it, I overlooked the value of n, here is not a violent one. The following provides a method with short code and less time, which is really nice

#include<stdio.h>
int a[1010];
int main()
{
    
    
	int n;
	while(~scanf("%d",&n))
	{
    
    
		int i,j=0,s=0;
		for(i=0;i<n;i++)
			scanf("%d",&a[i]);
		for(i=0;i<n-j;i++)
		{
    
    
			s+=a[i];
			while(s<=0)
			{
    
    
				j++;
				if(i<n-j)
					s+=a[n-j];
				else
					break;
			}
		}
		if(s>0)
			printf("%d\n",(n-j)%n+1);//这里记得对取模,因为会有n-j==n的情况
		else
			printf("-1\n");
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/Helinshan/article/details/108919021