-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathmaximize.cpp
48 lines (35 loc) · 1.11 KB
/
maximize.cpp
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
/*Maximize the rightmost element of an array in k operations in Linear Time*/
#include <iostream>
using namespace std;
// Function to calculate maximum value of
// Rightmost element
void maxRightmostElement(int N, int k, int p, int arr[]){
// Calculating maximum value of
// Rightmost element
while(k)
{
for(int i=N-2;i>=0;i--)
{
// Checking if arr[i] is operationable
if(arr[i]>= p)
{
// Performing operation of i-th element
arr[i]=arr[i]-p;
arr[i+1]=arr[i+1]+p;
break;
}
}
// Decreasing the value of k by 1
k--;
}
// Printing rightmost element
cout<<arr[N-1]<<endl;
}
// Driver Code
int main() {
// Given Input
int N = 4, p = 2, k = 5, arr[] = {3, 8, 1, 4};
// Function Call
maxRightmostElement(N, k, p, arr);
return 0;
}