Introduction
In this lab, we will be exploring JavaScript programming by completing a series of exercises designed to help build fundamental skills. From basic syntax and data types to more advanced concepts like asynchronous programming and functional programming, this lab will provide hands-on experience that will help you become a proficient JavaScript developer. Whether you're new to programming or looking to expand your skills, this lab will give you the tools you need to succeed.
Maximum Subarray Algorithm
To practice coding, open the Terminal/SSH and type node. This algorithm finds a contiguous subarray with the largest sum within an array of numbers. To implement this algorithm, follow these steps:
- Use a greedy approach to keep track of the current
sumand the current maximum,maxSum. SetmaxSumto-Infinityto ensure that the highest negative value is returned, if all values are negative. - Define variables to keep track of the maximum start index,
sMax, maximum end index,eMaxand current start index,s. - Use
Array.prototype.forEach()to iterate over the values and add the current value to thesum. - If the current
sumis greater thanmaxSum, update the index values and themaxSum. - If the
sumis below0, reset it to0and update the value ofsto the next index. - Use
Array.prototype.slice()to return the subarray indicated by the index variables.
Here's the JavaScript code for the algorithm:
const maxSubarray = (...arr) => {
let maxSum = -Infinity,
sum = 0;
let sMax = 0,
eMax = arr.length - 1,
s = 0;
arr.forEach((n, i) => {
sum += n;
if (maxSum < sum) {
maxSum = sum;
sMax = s;
eMax = i;
}
if (sum < 0) {
sum = 0;
s = i + 1;
}
});
return arr.slice(sMax, eMax + 1);
};
Here's an example of how to use the function:
maxSubarray(-2, 1, -3, 4, -1, 2, 1, -5, 4); // [4, -1, 2, 1]
Summary
Congratulations! You have completed the Maximum Subarray lab. You can practice more labs in LabEx to improve your skills.