题解 | #连续子数组的最大和(二)#

连续子数组的最大和(二)

https://www.nowcoder.com/practice/11662ff51a714bbd8de809a89c481e21

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param array int整型一维数组 
 * @return int整型一维数组
 */
export function FindGreatestSumOfSubArray(array: number[]): number[] {
    // write code here
    const cache: number[] = new Array(array.length)
    cache[0] = array[0]

    let max = cache[0]
    let resLeft = 0
    let resRight = 0

    let left = 0
    let right = 0

    for (let i = 1; i < array.length; i++) {
        right = i
        const currentMax = cache[i - 1] + array[i]
        cache[i] = Math.max(currentMax, array[i])
        
        if (currentMax < array[i]) {
            left = i
        }

        if (max <= cache[i]) {
            resLeft = left
            resRight = right
            max = cache[i]
        }
    }

    return array.slice(resLeft, resRight + 1)
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-28 12:15
点赞 评论 收藏
分享
05-09 13:22
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务