{"size": 1482, "ext": "js", "max_stars_repo_path": "src/sliding-window-maximum/index.js", "max_stars_repo_name": "alenny/leetcode", "max_stars_repo_stars_event_min_datetime": "2017-04-17T16:00:49.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-21T15:48:48.000Z", "max_issues_repo_path": "src/sliding-window-maximum/index.js", "max_issues_repo_name": "alenny/leetcode", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sliding-window-maximum/index.js", "max_forks_repo_name": "alenny/leetcode", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.0588235294, "max_line_length": 64, "alphanum_fraction": 0.4642375169}
/**
 * @param {number[]} numbers
 * @param {number} k
 * @return {number[]}
 */
const maxSlidingWindow = function (numbers, k) {
    if (numbers.length <= 1) {
        return numbers;
    }
    let maxIndex = 0;
    let nextMaxIndex = 1;
    let curr = 1;
    while (curr < k) {
        if (numbers[curr] > numbers[maxIndex]) {
            maxIndex = curr;
            nextMaxIndex = maxIndex + 1;
        } else if (numbers[curr] > numbers[nextMaxIndex]) {
            nextMaxIndex = curr;
        }
        ++curr;
    }
    let ret = [numbers[maxIndex]];
    while (curr < numbers.length) {
        if (maxIndex === curr - k) {
            if (numbers[nextMaxIndex] > numbers[curr]) {
                maxIndex = nextMaxIndex;
                nextMaxIndex = maxIndex + 1;
                for (let x = nextMaxIndex + 1; x <= curr; ++x) {
                    if (numbers[x] > numbers[nextMaxIndex]) {
                        nextMaxIndex = x;
                    }
                }
            } else {
                maxIndex = curr;
                nextMaxIndex = maxIndex + 1;
            }
        } else {
            if (numbers[curr] > numbers[maxIndex]) {
                maxIndex = curr;
                nextMaxIndex = maxIndex + 1;
            } else if (numbers[curr] > numbers[nextMaxIndex]) {
                nextMaxIndex = curr;
            }
        }
        ret.push(numbers[maxIndex]);
        ++curr;
    }
    return ret;
};

module.exports = maxSlidingWindow;