Question: You are playing a computer game called Best Alternating where you have to fight N monsters numbered from 1 to N . You are given
You are playing a computer game called "Best Alternating" where you have to fight N monsters numbered from to N
You are given an array of integers A where Ai represents the energy each monster has. It is given that the energy of a monster can also be negative.
You have to fight all monsters from monster numbered to monster numbered N in order and if you fight a monster numbered i your score will increase by Ai
Initially, you start with score as zero. But, you have a special ability called Alternating, which means that initially you have a positive sign to add all the monster's energies. Then, at any moment of time even before meeting the first monster you can decide to change this sign to and keep alternating this way for K times.
The final sum of energies obtained will be your score.
For example: If N K and A
We can alternate the sign when we meet the second monster. Hence score
Find the maximum score that you can get by playingoptimally
Note:
The sign chosen will remain the same until it is alternated.
Input Format
The first line contains an integer, N denoting the number of elements in A
The next line contains an integer, K denoting the given integer.
Each line i of the N subsequent lines where i N contains an integer describing Ai
Constraints
N
K
Ai
Sample Test Cases
Case
Input:
Output:
Explanation:
Given N K A
In this sample, if we don't alternate the sign at all, the answer will be as:
Case
Input:
Output:
Explanation:
Given N K A
This is the same as the first sample but here k is two, so we can alternate the sign twice and the answer will be calculated as the following:
Case
Input:
Output:
Explanation:
Given N K A
Initially, we start with a positive sign as the problem statements says, but when we meet the first monster we will alternate it to and add to the score.
Then we will alternate it to when meeting the second monster, and then to "when meeting the third monster, and thus, we have changed the sign K times.
Thus, the answer is calculated as follows:
Write this problem in Java code with explanation.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
