-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathArray Reduction Problem
73 lines (55 loc) · 1.79 KB
/
Array Reduction Problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Got this problem in HACKERRANK challenge
## 1. Array Reduction
-----
Anna has an array of n integers called sum.
She can reduce the array by 1 element by performig a move.
Each move consists of following three steps:
1. Pick two different elements.
2. Remove the two selected elements from array.
3. Add the sum of the two selected elements to the end of the array.
Each move has a cost associated with it.
The cost is equal to the sum of the two elements removed from the array during the move.
Anna wishes to calculate the minimum total cost of reducing her array to one element.
Function Description:
Complete the function `reductionCost`.
The function must return the minimum total cost of reducing the input array to one element.
`reductionCost` has following parameters:
num[num[0], ..., num[n-1]]: an array of integers.
Constraints:
- 2 <= n <= 10000.
- 0 <= num[i] <= 100000
Sample Input 0:
3
1
2
3
Sample Output 0:
9
Explanation 0:
Anna makes the following moves to reduce the num = [1, 2, 3]:
1. Removes 1 and 2 at cost1 = 1+2 = 3, resulting in num1 = [3, 3]
1. Removes 3 and 3 at cost2 = 3+3 = 6, resulting in num2 = [6]
When we sum up the cost at each reduction, we get 3+6 = 9
Sample Input 1:
3
4
6
8
Sample output 1:
28
SOLUTION
--------
--------
# Complete the 'reductionCost' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY num as parameters:
def reductionCost(nums):
# You can also solve this by heap data-structure
# Since this submission got accepted by Hackerrank so I did not use heap
summ = 0
while len(nums) != 0:
nums = sorted(nums)
summ += nums[0]+nums[1]
nums = [nums[0]+nums[1]+nums[2:]]
return summ