# C++ code to find minimum time needed to do all tasks

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements, and two other arrays k and x. The ith task takes A[i] time to complete. The given A is sorted in non-decreasing fashion. Amal takes at most k tasks and do each of them in x units of time instead of A[i]. (x < minimum of all A[i]). We have to find the minimum time needed to complete Amal's task. Amal cannot do more than one task simultaneously.

So, if the input is like A = [3, 6, 7, 10]; k = 2; x = 2, then the output will be 13, because the best option would be to do the third and the fourth tasks, spending x = 2 time on each instead of A[2] and A[3]. Then the answer is 3 + 6 + 2 + 2 = 13.

## Steps

To solve this, we will follow these steps −

x := k * x
n := size of A
for initialize i := 0, when i < n - k, update (increase i by 1), do:
t := A[i]
x := x + t
return x

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A, int k, int x){
x = k * x;
int n = A.size();
for (int i = 0; i < n - k; i++){
int t = A[i];
x += t;
}
return x;
}
int main(){
vector<int> A = { 3, 6, 7, 10 };
int k = 2;
int x = 2;
cout << solve(A, k, x) << endl;
}

## Input

{ 3, 6, 7, 10 }, 2, 2

## Output

13
Updated on 30-Mar-2022 14:14:31