[Algorithm] Maximum Contiguous Subarray algorithm implementation using TypeScript / JavaScript

本文探讨了最大子数组问题的解决方案,首先介绍了朴素的O(n^3)算法,然后深入讲解了动态规划方法,通过最大连续子数组算法实现更高效的求解。文章通过具体示例说明了算法的运行过程,对比了不同情况下的最优解。

Naive solution for this problem would be caluclate all the possible combinations:

const numbers = [1, -3, 2 - 5, 7, 6, -1, -4, 11, -23];

// O(n^3)
const findMaxSubAry = numbers => {
  let answer = Number.MIN_VALUE;
  /**
   * Calculate all the possible values and pick the max one
   * All possible values should be
   * length = 1, 2, ,3 ... n
   *  Pick differnet start point
   */

  // For different lenght
  for (let l = 0; l < numbers.length; l++) {
    // O(n)
    // For different start
    for (let s = 0; s < l; s++) {
      // O(n)
      if (s + l >= numbers.length) {
        break;
      }
      let sum = 0;
      for (let i = s; i < s + l; i++) {
        // O(n)
        sum += numbers[i];
      }

      answer = Math.max(answer, sum);
    }
  }

  return answer;
};

console.log(findMaxSubAry(numbers));  // 19

 

 

The maximum subarray problem is one of the nicest examples of dynamic programming application.

In this lesson we cover an example of how this problem might be presented and what your chain of thought should be to tackle this problem efficiently.

 /**
  * Maximum Contiguous subarray algorithm
  * 
  * Max(i) = Max(i-1) + v(i)
  * Max(i-1) < 0 ? v(i) : Max(i-1)
  * 
  * Combining
---------
maxInc(i) = maxInc(i - 1) > 0 ? maxInc(i - 1) + val(i) : val(i)
max(i) = maxInc(i) > max(i - 1) ? maxInc(i) : max(i - 1)
  */
function maxSumSubArray(arr) {
  /**
   *   inx  | val   |  max_inc    | max 
   *          0       0            0
   *    0     -2      0            0
   *    1     -3      0            0
   *    2     4       4            4     ---> start = 2
   *    3     -1      3            4
   *    4     -2      1            4
   *    5     1       2            4
   *    6     5       7            7     ---> end  = 6
   *    7     -3      4            7             
   */

  let val = 0, max_inc = 0, max = 0, start = 0, end = 0;

  for (let i = 1; i < arr.length; i++) {
    val = arr[i];
    max_inc = Math.max(max_inc + val, val);
    max = Math.max(max, max_inc);

    if (val === max_inc) {
      start = i;
    }

    if (max === max_inc) {
      end = i;
    }
  }

  if (end === 0) {
    end = start;
  }
  console.log(start, end);
  return arr.slice(start, end + 1);
}

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

 

转载于:https://www.cnblogs.com/Answer1215/p/10227039.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值