UNPKG

algs4js

Version:

Basic algorithms and data structures implemented with es6

60 lines (48 loc) 2.15 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _LogUtil = require('../util/LogUtil'); var _LogUtil2 = _interopRequireDefault(_LogUtil); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Class MaxSubArray * * Exposes static fucntionality for finding the maxium subarray sum through dynamic programming */ var MaxSubArray = function () { function MaxSubArray() { _classCallCheck(this, MaxSubArray); } _createClass(MaxSubArray, null, [{ key: 'find', /** * Finds the maximum subarray for a given array. Uses the following dynamic programming * algorithm: * * S(0) = A(0); * S(i) = max(S(i-i) + A(i), A(i)) * * @param {number[]} the input array of numbers * @returns {number} the maxium subarray sum */ value: function find(arr) { _LogUtil2.default.debug('Finding max of arr ' + arr); if (!Array.isArray(arr) || arr.length === 0) { return null; } var sum = [arr[0]]; for (var i = 1; i < arr.length; i++) { sum[i] = Math.max(sum[i - 1] + arr[i], arr[i]); } _LogUtil2.default.debug('Resulting S[i]: ' + sum); var maxSum = Math.max.apply(Math, sum); _LogUtil2.default.debug('Found max sum to be: ' + maxSum); return maxSum; } }]); return MaxSubArray; }(); exports.default = MaxSubArray;