[Algorithm] Maximum Contiguous Subarray algorithm implementation using TypeScript / JavaScript
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Algorithm] Maximum Contiguous Subarray algorithm implementation using TypeScript / JavaScript相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
以报复为由,新版本Conti勒索软件源代码遭泄露,6万余条内部消息公之于众