Quick actions

cmd+k|ctrl+k

Navigation

Languages

algo js

Snippet info

Language

JavaScript

Visibility

public

Author

goodnewsj62

Created

2024-10-28T14:18:44.671966Z

Updated

2024-10-28T14:18:57.293006Z

function printSubArrays(arr, k){
   //get the size the of the array
   let length = arr.length;
   
   //traverse through the array
   for(let i = 0; i < length; i++){
      //temp variables to store the sum and elements
      let tempArr = [arr[i]];
      let sum = arr[i];
     
      //traverse through the every next element after i
      for(let j = i+1; j < length; j++){    
         sum += arr[j];
         tempArr.push(arr[j]);
         
         //if sum is equal to k then print the array.
         if(sum === k){
           console.log(tempArr);
         }
      }
   }
}

printSubArrays([3,4,-7,1,3,3,1,-4], 7);


const largestSum  = (arr)=>{
    let max_sum =  -Infinity;
    let sum = 0;
    
    for (let i = 0;  i < arr.length; i++){
        sum += arr[i];
        
        max_sum = Math.max(max_sum,  sum);
        
        if (sum < 0){
            sum =  0;
        }
    }
    
    return max_sum;
}

console.log(largestSum([-2, -3, 4, -1, -2, 1, 5, -3]));



INFO