
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Minimum Time Needed to Complete All Tasks in C++
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