Home  >  Article  >  Web Front-end  >  JavaScript program to calculate size of subarray with maximum sum

JavaScript program to calculate size of subarray with maximum sum

王林
王林forward
2023-09-15 22:29:041230browse

JavaScript 程序计算具有最大和的子数组的大小

A JavaScript program to find the maximum and subarray sizes is a common problem in the world of programming, especially in web development. The problem statement involves finding the contiguous subarray with the maximum sum in a given one-dimensional array of integers. This is also known as the maximum subarray problem. Solving this problem is useful in a variety of applications, such as financial analysis, stock market forecasting, and signal processing.

In this article, we will see the algorithm and size of subarrays to achieve maximum sum using JavaScript. We will first discuss the problem in detail and then move on to develop a step-by-step solution using the JavaScript programming language. So let’s get started!

Problem Statement

Given an array of integers, we must find the length of the subarray with the largest sum.

For example, suppose we have an array of integers: [1, -2, 1, 1, -2, 1], the largest subarray is [1, 1], and the sum is 2. We can find the length of this subarray by subtracting the start index from the end index and adding 1. In this example, the starting index is 0 and the ending index is 1, so the length of the subarray is 2.

Another example is an array of all negative integers: [-2, -5, -8, -3, -1, -7]. In this case, the largest subarray will be [-1] and the sum will be -1. Since all elements are negative, the subarray with the smallest absolute value has the largest sum. Therefore, the length of the subarray is -1.

It should be noted that there can be multiple maximum subarrays, and the sum of each subarray is the same. However, we only need to find one of them.

algorithm

step 1

We first initialize four variables: "maxSum" is "-Infinity", "currentSum" is "0", "start" is "0", and end is "0". We'll use 'maxSum' to keep track of the largest sum we've seen so far, 'currentSum' to calculate the sum of the subarray for our current iteration, 'start' to keep track of the starting index of the subarray, and 'end' to keep track of The end index of the subarray.

Step 2

Then we use a "for" loop to iterate through the array. For each element in the array, we add it to "currentSum". If 'currentSum' is greater than 'maxSum', we update 'maxSum' to 'currentSum' and set 'end' to the current index.

Step 3

Next, we use a while loop to check if "currentSum" is less than "0". If so, we subtract the value at "start" from "currentSum" and add 1 to "start". This ensures that we always have a contiguous subset of the array.

Step 4

Finally, we check if "currentSum" is equal to "maxSum" and if the size of the current subarray is greater than the previous subarray. If so, we update "end" to the current index.

Step 5

The time complexity of this algorithm is O(n) and the space complexity is O(1), which is optimal for this problem.

Example

The following JavaScript program is designed to solve the problem of using two pointers, start and end, to find the contiguous subarray with the largest sum in an integer array. The algorithm initializes the maximum sum to negative infinity, the current sum to zero, and the start and end indexes to zero. It adds each element to the current sum and updates the maximum sum and end index if the current sum is greater than the maximum sum. It removes elements from the beginning of the subarray until the current sum is no longer negative, then updates the end index if the current sum is equal to the maximum sum and the length of the subarray is greater than the length of the previous subarray. Finally, it returns the length of the largest subarray by subtracting the start index from the end index and adding 1.

function maxSubarraySize(arr) {
   let maxSum = -Infinity;
   let currentSum = 0;
   let start = 0;
   let end = 0;
   for (let i = 0; i < arr.length; i++) {
      currentSum += arr[i];
      if (currentSum > maxSum) {
         maxSum = currentSum;
         end = i;
      }
      while (currentSum < 0) {
         currentSum -= arr[start];
         start++;
      }
      if (currentSum === maxSum && i - start > end - start) {
         end = i;
      }
   }
   return end - start + 1;
} 
// Example usage:
const arr = [1, -2, 1, 1, -2, 1];
console.log("Array:", JSON.stringify(arr));
const size = maxSubarraySize(arr);
console.log("Size of the Subarray with Maximum Sum:", size);

Let's see the output with some examples for better understanding.

Example 1

Input - Given an integer array, a[]= {1, -2, 1, 1, -2, 1}

Output 2

Description - A subarray with consecutive elements with a maximum sum of {1, 1}. Therefore, the length is 2.

Example 2

Input - Given an array of all negative integers, a[]= {-2, -5, -8, -3, -1, -7}

Output-1

Explanation - In this case, the maximum subarray will be [-1] and the sum will be -1. Therefore, the length of the subarray is -1.

in conclusion

The size of the subarray with the largest sum is a common question when working with arrays in programming. The algorithm to solve this problem involves iterating over the array and keeping track of the current sum and the largest sum seen so far. By implementing this algorithm in JavaScript, we can write a program that efficiently finds the size of the subarray that has the largest sum for any given array of integers.

The above is the detailed content of JavaScript program to calculate size of subarray with maximum sum. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete