首页 > 编程语言 > 详细

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

时间:2019-01-06 10:25:08      阅读:138      评论:0      收藏:0      [点我收藏+]

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)
  */

const numbers = [-2, 1, 3, 4, -1, 2, 1, -5, 4];
function maxSubArray (ary) {
    if (ary.length === 0) {
        return [];
    }

    let maxInc = ary[0];
    let max = ary[0];
    let maxStartInx = 0;
    let maxEndInx = 0;

    for (let i = 0; i < ary.length; i++) {
        const val = ary[i];

        maxInc = Math.max(maxInc + val, val);
        max = Math.max(max, maxInc);

        if (val === max) {
            maxStartInx = i
        }

        if (maxInc === max) {
            maxEndInx = i
        }

        return Array.slice(maxStartInx, maxEndInx + 1)
    }
}
console.log(‘maxSubArray‘, maxSubArray(numbers));

 

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

原文:https://www.cnblogs.com/Answer1215/p/10227039.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!