2021-03-29: Unordered array arr, there are as many sub-arrays as -1 and 1, what is the length of the longest sub-array?

2021-03-29: Unordered array arr, there are as many sub-arrays as -1 and 1, what is the length of the longest sub-array?

Fu Da's answer 2021-03-29:

[1, -1, 2, 3, -4, -1, 9] becomes [1, -1, 0, 0, 0, -1, 0], the length of the longest sub-array whose cumulative sum is equal to 0 is The required value.
Find the prefix sum and save the map.

The code is written in golang. code show as below:

package main

import "fmt"

func main() {
    arr := []int{1, -1, 2, 3, -4, -1, 9}
    ret := maxLength(arr)
    fmt.Println(ret)
}

func maxLength(arr []int) int {
    if len(arr) == 0 {
        return 0
    }
    // key:前缀和
    // value : 0~value这个前缀和是最早出现key这个值的
    mmap := make(map[int]int)
    mmap[0] = -1 // important
    llen := 0
    sum := 0
    for i := 0; i < len(arr); i++ {
        if arr[i] == 1 {
            sum++
        } else if arr[i] == -1 {
            sum--
        }
        if _, ok := mmap[sum]; ok {
            llen = getMax(i-mmap[sum], llen)
        }
        if _, ok := mmap[sum]; !ok {
            mmap[sum] = i
        }
    }
    return llen
}

func getMax(a int, b int) int {
    if a > b {
        return a
    } else {
        return b
    }
}

The execution results are as follows:
Insert picture description here


comment

Guess you like

Origin blog.51cto.com/14891145/2676901