Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
You are given an array A consisting of N numbers. In one move you can delete either the
first two, the last two, or the first and last elements of A. No move can be performed if
the length of A is smaller than 2. The result of each move is the sum of the deleted
elements.
Write a function:
int solution (int A[], int N);
that, given an array A of N integers, returns the maximum number of moves that can be
performed on A, such that all performed moves have the same result.

What I have tried:

C++
int solution(int A[], int N) {
    if (N < 2) {
        return 0;
    }

    int max_moves = 0;
    int left = 0;
    int right = N - 1;
    int target_sum = 0;

    while (left < right) {
        int current_sum = A[left] + A[right];
        
        if (current_sum == target_sum) {
            max_moves++;
            left += 2;
            right -= 2;
        } else if (current_sum < target_sum) {
            left++;
        } else {
            right--;
        }
    }

    return max_moves;
}
Posted
Updated 3-Aug-23 21:22pm
v2
Comments
OriginalGriff 4-Aug-23 2:57am    
And?
What does it do that you didn't expect, or not do that you did?
What have you tried to do to find out why?
Are there any error messages, and if so, where and when? What did you do to make them happen?

This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with.
Use the "Improve question" widget to edit your question and provide better information.
Patrice T 4-Aug-23 5:06am    
An you have a question or a problem ?

1 solution

You might try recursion.
In your function, iteratively try the allowed moves (computing the result). At each attempt recursively call the function itself (passing the result). You have the stop condition when no further move is available (because either the number of remaining items is less than 2, or none of the available moves could produce the same result of the 'parent move').
 
Share this answer
 
Comments
Patrice T 4-Aug-23 5:04am    
+5
CPallini 4-Aug-23 5:17am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900