C++ code to count years to reach certain rank in an army

Suppose we have an array D with n-1 elements and two values a and b. In an army, there are n ranks numbered from 1 to n. One needs D[i] years to rise from rank i to rank i+1. Amal has just reached new rank 'a' but he wants to reach rank 'b'. We have to count the number of years he will need to reach his goal.

So, if the input is like D = [5, 6]; a = 1; b = 3, then the output will be 11.

To solve this, we will follow these steps −

n := size of D
s := 0
for initialize i := a - 1, when i < b - 1, update (increase i by 1),
do:
s := s + D[i]
return s

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> D, int a, int b){
int n = D.size() + 1;
int s = 0;
for (int i = a - 1; i < b - 1; i++){
s = s + D[i];
}
return s;
}
int main(){
vector<int> D = { 5, 6 };
int a = 1;
int b = 3;
cout << solve(D, a, b) << endl;
}

Input

{ 5, 6 }, 1, 3

Output

11

Updated on: 15-Mar-2022

116 Views