# C++ code to find money after buying and selling shares

C++Server Side ProgrammingProgramming

Suppose we have two arrays A of size n, and B of size m, and another number r. There are n opportunities to buy shares. The i-th of them allows to buy as many shares as we want, ith share price is A[i]. And also there are m opportunities to sell shares. The i-th of them allows to sell as many shares as we want, sell price of ith share is B[i]. We can't sell more shares than we have. If we have r amount of money and no existing share, we have to find the maximum number of money we can hold after buying and selling.

So, if the input is like A = [4, 2, 5]; B = [4, 4, 5, 4]; r = 11, then the output will be 26, because we have 11 amount of money. It's optimal to buy 5 shares of a stock at the price of 2, and then to sell all of them at the price of 5. Thus we can get 26 at the end.

## Steps

To solve this, we will follow these steps −

n := size of A
an := 1100
bn := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
if an > A[i], then:
an := A[i]
for initialize i := 0, when i < m, update (increase i by 1), do:
if bn < B[i], then:
bn := B[i]
if bn > an, then:
r := bn * (r / an) + (r - (r / an) * an)
return r

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A, vector<int> B, int r){
int n = A.size(), m = B.size();
int an = 1100, bn = 0;
for (int i = 0; i < n; i++){
if (an > A[i])
an = A[i];
}
for (int i = 0; i < m; i++){
if (bn < B[i])
bn = B[i];
}
if (bn > an){
r = (bn) * (r / an) + (r - (r / an) * an);
}
return r;
}
int main(){
vector<int> A = { 4, 2, 5 };
vector<int> B = { 4, 4, 5, 4 };
int r = 11;
cout << solve(A, B, r) << endl;
}

## Input

{ 4, 2, 5 }, { 4, 4, 5, 4 }, 11

## Output

26
Updated on 29-Mar-2022 11:11:01