You are analyzing the market trend of amazon stocks.An AWS service model retuned array of integers ,PnL(Profit and loss) for your portfolio representing the ith month,you will
either gain or lose PnL[i].All reported PnL values are positive represneting gains.
As part of analysis you will perform the following operations in PnL array any number of times:
Choose any month i(0<=i<=n) and multiply PnL[i] by -1
find maximum number of months you can afford to face a loss,i.e. having a negative PnL ,such that the ccumulative PnL for each of the n months remains strictly positive i.e. remains greater than 0
note :- the cumulative PnL for the ith month is defined as the sum of PnL from the starting month upto the ith month.For example the cumulative PnL for the PnL= [3,-2,5,-6,1] is [3,1,6,0,1]
write a javascript code such that function description
getMaxNgetaivePnL has parameters int PnL[n]: an array of integers
INput format for custom testing:-
the first line contains an integer , n,the number of elements in PnL
each line i of the n subsequent lines (where 0<=i<=n) conatins an integer ,PnL[i]
`function getMaxNegativePnL(PnL) {
let n = PnL.length;
let totalSum = PnL.reduce((acc, val) => acc + val, 0);
let minPrefixSum = 0;
let currentPrefixSum = 0;
let negativeCount = 0;
for (let i = 0; i < n; i++) {
currentPrefixSum += PnL[i];
minPrefixSum = Math.min(minPrefixSum, currentPrefixSum);
}
for (let i = 0; i < n; i++) {
if (totalSum - 2 * PnL[i] > 0) {
totalSum -= 2 * PnL[i];
negativeCount++;
}
}
return negativeCount;
}
// Custom testing input
const PnL = [3, 2, 5, 6, 1];
console.log(getMaxNegativePnL(PnL)); // Expected output: Depends on input
const PnL2 = [3, 2, 1, 4, 5, 6];
console.log(getMaxNegativePnL(PnL2)); // Expected output: Depends on
input
`
expected output was 2 ours was 3
You need to sign in to view this answers
Leave feedback about this