Advertisement
informaticage

Equal side array, linear solution

Nov 20th, 2022
1,436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function makePSA(arr) {
  2.     const PSA = new Array(arr.length + 1);
  3.     let sum = 0;
  4.  
  5.     for (let i = 0; i <= arr.length; i++) {
  6.         PSA[i] = sum;
  7.         sum += arr[i];
  8.     }
  9.  
  10.     return PSA;
  11. }
  12.  
  13. function queryPSA(PSA, start, end) {
  14.     return (PSA[end] - PSA[start]) || 0;
  15. }
  16.  
  17. function findEvenIndex(arr) {
  18.     const PSA = makePSA(arr);
  19.  
  20.     for (let index = 0; index <= arr.length; index++) {
  21.         let leftSum = queryPSA(PSA, 0, index);
  22.         let rightSum = queryPSA(PSA, index + 1, arr.length);
  23.  
  24.         console.log(index, leftSum, rightSum);
  25.  
  26.         if (leftSum === rightSum) {
  27.             return index;
  28.         }
  29.     }
  30.  
  31.     return -1;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement