how to get maximum sub array in javascript - javascript

var maxSubArray = function(nums) {
let sum = 0,
result = 0;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(0, sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
let nums = [-2,1,-3,4,-1,2,1,-5,4];
console.log(maxSubArray(nums));
Question
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
But my test case fail
Input
[-1]
Output
0
Expected
-1
and one more test case fails
Input
[-2,-1]
Output
0
Expected
-1
Answer
var maxSubArray = function(nums) {
let sum = 0,
result = 0,
max=nums[0];
for (let i = 0; i < nums.length; i++) {
sum = Math.max(0, sum + nums[i]);
result = Math.max(sum, result);
if(nums[i] > max){
max = nums[i];
}
}
return result <=0 ? max :result ;
};

Your result should start at -Infinity (or at the value of the first item of the array), otherwise an array containing all negative numbers won't give a proper result. The calculation of sum inside the loop should also use Math.max(nums[i], sum + nums[i]);, otherwise if you pass 0 to Math.max, the current running total will always be at least 0, resulting in an incorrect answer when the passed array contains all negative values.
var maxSubArray = function(nums) {
let sum = 0,
result = -Infinity;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(nums[i], sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
console.log(
maxSubArray([-2,1,-3,4,-1,2,1,-5,4]),
maxSubArray([-1]),
maxSubArray([-2,-1]),
);

var maxSubArray = function(nums) {
let sum = 0,
result = -Infinity;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(nums[i], sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
console.log(
maxSubArray([-2,1,-3,4,-1,2,1,-5,4]),
maxSubArray([-1]),
maxSubArray([-2,-1]),
);
<!-- begin snippet: js hide: false console: true babel: false -->

Related

How to add 5 random numbers which are less than 10?

I've created two functions. One to create 5 random numbers to push them into an array. And another one to sum up the numbers. The random number generator is working and making an array perfectly. But the sum is not accurate. I'm unable to find where the problem is.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
console.log(pushIntoArray());
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
let arr = pushIntoArray();
console.log(sumNum(arr));
Because you are logging a different set of array values and checking the sum of different set of array values.
I have changed your console.log statement.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
let arr = pushIntoArray();
console.log(arr);
console.log(sumNum(arr));
You are not performing the sum on the array that you logged in the console. What you are logging is
console.log(pushIntoArray()); // This is displayed in the console
But then you are generating a ney array by calling
let arr = pushIntoArray();
BUT you are performing the sum on the arr array not the one that is displayed in the console.
console.log(sumNum(arr)); // you did not console.log(arr)
The function works correctly, you are just calling it on the wrong thing.
the function is working correctly but you are logging a different array of random numbers and calculating the sum of a different array.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
// this array is different (this is not passed to the sumNum function)
console.log(pushIntoArray());
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
// this array is different
let arr = pushIntoArray();
console.log("sum of array:", arr)
console.log(sumNum(arr));

trying to figure out how to convert an array of strings to an array of numbers

i'm having issues figuring out how to transform an array of strings to an array of integers.
the following array for example :
['137','364','115','724']
What I essentially have to do is remove and return the largest number in each element and add it to the second largest number, the third largest number and so on depending on the length of the numbers. (The elements in the array will always be the same length)
for example:
1st largest number is 7, (remove largest number from each element leaving [13,34,11,24])
2nd largest number left is 4 (remove largest number from each element again [1,3,1,2])
3rd largest number left is 3 (no more numbers left to remove at this point)
7 + 4 + 3
This is what I have so far:
function sW(his) {
// Write your code here
for (var i = 0; i < history.length; i++ ){
var something = history[i].split('')
console.log(something)
console.log(Math.max(parseInt(something)))
console.log(parseInt(something))
}
}
This isn't working so far because when I attempt to parseInt/ return the max of the number at each index, it will always just return the first number. Would appreciate some help, thanks!
Here's one solution:
function slotWheels(arr) {
// Sort all the numbers in the array
// ['137','364','115','724'] -> ['731', '643', '511', '742']
const sorted = arr.map(e => [...e].sort((a, b) => b - a).join(''));
let sum = 0;
for(let i = 0; i < sorted[0].length; i++) {
// find out the max number of each numbers at the same position, and add it to sum
sum += Math.max(...sorted.map(e => e[i]));
}
return sum;
}
console.log(slotWheels(['137','364','115','724']));
strs = ['1234','4231','1423','3241']
result = strs
.map(str => str.split(''))
.map(arr => arr.sort((a, b) => b - a))
.reduce(
(acc, item) => acc.map((num, j) => Math.max(num, item[j])),
new Array(strs[0].length).fill(0)
)
.reduce((acc, num) => acc + num, 0)
console.log(result);
I think this one could help:-
function slotWheels(history) {
// Write your code here
if (history[0] && history[0].length > 0) {
let maxLength = history[0].length;
let sumArray = [];
for (var j = 0; j < maxLength; j++) {
let max = Number.MIN_SAFE_INTEGER;
let maxArray = [];
for (var i = 0; i < history.length; i++ ){
var something = Math.max(... history[i].split('').map (str => {return parseInt(str)}));
history[i] = ('' + history[i]).replace (something, '');
maxArray.push (something);
}
sumArray.push (Math.max (... maxArray));
}
var returnSum = 0;
for (let i = 0; i < sumArray.length; i++) {
returnSum += sumArray[i];
}
return returnSum;
} else {
return 0;
}
}

Javascript - sum of string decimals

i have and array of string that are decimals. I need to iterate the array and get the sum of them. For example
function check() {
let arr = ["1,50", "1,50"];
let sum1 = 0;
let sum2 = "0";
let sum3 = 0
for (let i = 0, length = arr.length; i < length; i++) {
sum1 += +arr[i];
sum2 += +arr[i];
sum3 += arr[i];
}
console.log(sum1, sum2, sum3)
//sum1 = NaN
//sum2 = '0NaNNaN'
//sum3 = 01,501,50
}
sum should be 3 or 3,00.
You can use reduce() for sum and replace() to replace , with ..
let arr = ["1,50", "1,50"];
const result = arr.reduce((r, e) => r + +e.replace(',', '.'), 0)
console.log(result)

Where am I going wrong? Trying to print no of times number is added before returning single digit

function AdditivePersistence(num) {
var count = 0;
while (num.toString().length > 1) {
count++;
var num = calcVal(num);
}
return count;
function calcVal(str) {
var sum = 0;
var arr = str.toString().split("");
for (var i of arr) {
sum = sum + arr[i];
}
return parseInt(sum.toString());
}
}
console.log(AdditivePersistence(2233));
calcValue function returns sum of the array numbers and while loop repeats until returned number length is 1.
When you use for...of, i is the digit and not the index of the digit. In addition you need to parse the digit.
sum = sum + parseInt(i, 10); // i is the number, not the index
Since you used i as an index, the result of calcVal() was always a string of length > 2, which means an infinite loop in your case.
Fixed code:
function AdditivePersistence(num) {
var count = 0;
while (num.toString().length > 1) {
count++;
num = calcVal(num);
}
return count;
function calcVal(str) {
var sum = 0;
var arr = str.toString().split("");
for (var i of arr) {
sum = sum + parseInt(i, 10); // i is the number, not the index
}
return sum;
}
}
console.log(AdditivePersistence(2233));

Javascript sum of arrays and average

I have an issue with getting the sum of two arrays and combining their averages while rounding off.
I don't want to hardcode but rather pass two random arrays. so here is the code but it keeps returning NaN
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
arr = [];
a = [];
b = [];
arr[0] = a;
arr[1] = b;
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
If you wanted to do it a bit more functionally, you could do something like this:
function sumAverage(arrays) {
const average = arrays.reduce((acc, arr) => {
const total = arr.reduce((total, num) => total += num, 0);
return acc += total / arr.length;
}, 0);
return Math.round(average);
}
console.log('sum average:', sumAverage([[1,2,3], [4,5,6]]));
Just try this method..this kind of issues sometimes occured for me.
For example
var total = 0;
total = total + sum / a.length;
And every concat use this method..
Because you are assigning the value [] with the same name as the argument? This works, see jFiddle
function sumAverage(arr) {
var result = 0;
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for(var j = 0; j < a.length; j++ ){
sum += a[j] ;
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for(var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
document.write(sumAverage([[2,3,4,5], [6,7,8,9]]));
As said in comments, you reset your arguments...
Use the variable "arguments" for dynamic function parameters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
I suggest to use two nested loops, one for the outer array and one for the inner arrays. Then sum values, calculate the average and add averages.
function sumAverage(array) {
var result = 0,
sum,
i, j;
for (i = 0; i < array.length; i++) {
sum = 0;
for (j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
result += Math.round(sum / array[i].length);
}
return result;
}
console.log(sumAverage([[2, 3, 4, 5], [6, 7, 8, 9]])); // 12
The problem is that you are emptying arr by saying arr = [].
Later, you are iterating over a which is empty too.
Again when you say total += sum / a.length;, sum is 0 and a.length is 0 so 0/0 becomes NaN. Similarly for math. Adding Nan to NaN is again NaN and that's what you get.
Solution is to not empty passed arr and modify your code like below:
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total = sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math = add / b.length;
result = math + total;
result = Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
Basically I see a mistake here:
arr[0] = a; arr[1] = b;
That should be
a= arr[0]; b= arr[1];
and then remove:
arr = [];
I suggest you write your function like this:
function sum(arr) {
var arr1 = arr[0]
var sum1 = 0;
arr1.map(function(e){sum1+=e});
var arr2 = arr[1]
var sum2 = 0;
arr2.map(function(e){sum2+=e});
return Math.round(sum1/arr1.length + sum2/arr2.length);
}

Categories