Given an array of numbers and k. Divide the array into k continuous subarrays so that sum of each subarray is odd.
Answers
Answered by
1
Example, let the array A = [1,2,3]
Then, we can remove 1 and 2, add both of them and keep the sum back in array. Cost of this step would be (1+2) = 3.
So A = [3,3], Cost = 3
In second step, we can remove both elements from the array and keep the sum back in array again. Cost of this step would be 3 + 3 = 6.
So, A = [6], Cost = 6
So total cost turns out to be 9 (6+3).
I tried sorting the array, and adding the elements from decreasing to increasing, but it fails if there are duplicate elements.
Pseudo code of my algorithm
sort(Array)
cost = 0
for(i=0; i<Array.length - 1; i++) {
Array[i+1] = Array[i] + Array[i+1]
cost = cost + Array[i+1]
}
The algorithm mentioned above was not working. I came up with a possible case where it may fail. If the Array = [5, 5, 5, 5], then Cost = 45, according to the above algorithm.
However if we sum the first two elements and last two elements, and then sum the remaining two elements, then the total cost turns out to be 40. (In first step, cost = 10*2, and in next step another 20).
PLEASE MAKE ME AS A BRAINLIST ANSWER
☺️
Similar questions
Chemistry,
6 months ago
Accountancy,
6 months ago
English,
6 months ago
Computer Science,
11 months ago
Computer Science,
11 months ago
Math,
1 year ago
History,
1 year ago