I had a problem that I tried to solve. Some of the test cases were successful, while others were not.
Requirements:
You are given a list of N transfers (numbered from 0 to N−1) between two banks: bank A and bank B. The K-th transfer is described by two values:
- R[K] (either "A" or "B") representing the recipient (the bank the transfer is sent to);
- V[K] denoting the value sent via the transfer.
All transfers are completed in the order they appear on the list. The banks do not want to go into debt (in other words, their account balance may not drop below 0). What minimum initial account balance in each bank is necessary in order to complete the transfers?
Write a function:
function solution(R, V);
that, given a string R and an array of integers V, both of length N, returns an array of two integers. The integers should represent the minimum initial account balances for banks A and B in the following order: [bank A, bank B].
The result array should be returned as an array of integers.
Write an efficient algorithm for the following assumptions:
- string R and array V are both of length N;
- N is an integer within the range [1..100,000];
- each element of array V is an integer within the range [1..10,000];
- string R consists only of the characters "A" and/or "B".
I passed the following test cases:
- Given R = "BAABA" and V = [2, 4, 1, 1, 2], the function should return [2, 4].
- Given R = "ABAB" and V = [10, 5, 10, 15], the function should return [0, 15].
- Given R = "B" and V = [100], the function should return [100, 0].
- Given R = "ABBA" and V = [1, 1, 1, 1], the function should return [1, 1].
I failed the following test cases:
Could you please advise me on how to replicate those test cases?
My test has been completed, but I am eager to learn how to replicate those results. it's not homework
Thanks in Advance.
function solution(R, V) {
let min_A = 0;
let min_B = 0;
let balance = 0;
let arr = [];
let final = [];
R = R.split('');
for (var i = 0; i < R.length; i ) {
arr.push({
receiver: R[i],
amount: V[i],
});
}
arr.map((k) => {
if (k.receiver == 'A') {
balance = k.amount;
min_B = Math.min(-balance, min_B);
} else {
balance -= k.amount;
min_A = Math.min(balance, min_A);
}
});
final.push(Math.abs(min_A), Math.abs(min_B));
console.log(final);
console.log(min_A, min_B);
}
solution('ABBA', [1, 1, 1, 1]);
CodePudding user response:
Your issue, as far as I can see, stems from how you've defined the minimum values. You define min_a
and min_b
to be 0
, you should instead define them to be their first matching values (and do this by setting them to placeholder values outside of their valid range so you can easily check). Here's how you should modify the code:
let min_A = "";
let min_B = "";
...
balance = k.amount;
if (min_B === "") {
min_B = -balance;
} else {
min_B = Math.min(-balance, min_B);
}
...
balance -= k.amount;
if (min_A === "") {
min_A = balance;
} else {
min_A = Math.min(balance, min_A);
}