Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sliding window #4

Open
Jinsujin opened this issue Jun 27, 2023 · 0 comments
Open

Sliding window #4

Jinsujin opened this issue Jun 27, 2023 · 0 comments

Comments

@Jinsujin
Copy link
Owner

Jinsujin commented Jun 27, 2023

길이가 정해진 윈도우를 만들어서, 옆으로 한칸 밀면서 연산해 가는 것

예) 연속된 N 일 동안 최대 매출 기록 구하기

  1. 미리 arr[0] ~ arr[2] 의 값을 구해둔다.
  2. for [3] 부터 배열의 끝까지 돈다
    • [0] 의 값을 빼고, 현재 값인 [i] 를 더한다
    • 전체합 + arr[i]
    • 전체합 - arr[i-K]
 func solution(_ input: [Int], K: Int) -> Int {
    var answer = Array(input[0..<K]).reduce(0, +)
		var sum = answer
    
    for i in K..<input.count {
        sum += input[i] - input[i-K]
        answer = max(answer, sum)
    }
    return answer
}
// 56
solution([12, 15, 11 ,20, 25, 10, 20, 19, 13, 15], K: 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant