码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-06 10:37:13      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:present   ret   types   bar   color   ogr   res   console   ini   

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

标签:present   ret   types   bar   color   ogr   res   console   ini   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!