Skip to content

Commit dcf0163

Browse files
committed
[Gold IV] Title: A[j]-A[i]+A[l]-A[k], Time: 432 ms, Memory: 143620 KB -BaekjoonHub
1 parent 651b653 commit dcf0163

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import Foundation
2+
3+
let n = Int(readLine()!)!
4+
let arr = readLine()!.split { $0 == " " }.map { Int(String($0))! }
5+
6+
var leftBest = [Int](repeating: Int.min, count: n)
7+
var rightBest = [Int](repeating: Int.min, count: n)
8+
9+
// (-A[i] + A[j]) + (-A[k] + A[l])
10+
// 최소 i를 찾는다.
11+
// 최대 l를 찾는다.
12+
13+
// 왼쪽에서부터 최대차이
14+
var minLeft = arr[0]
15+
leftBest[0] = Int.min // j=0에서는 i<j 불가능
16+
17+
for j in 1..<n {
18+
leftBest[j] = max(leftBest[j-1], arr[j] - minLeft)
19+
// 방금 지나친 j는 다시 사용하지 않으므로, 다음의 j보다 이전이다.
20+
// 따라서 과거가 된 j를 i로 취급해 최솟값으로 활용할 수 있다.
21+
minLeft = min(minLeft, arr[j])
22+
}
23+
24+
var maxRight = arr[n-1]
25+
rightBest[n-1] = Int.min // j=0에서는 i<j 불가능
26+
27+
28+
// n >= 4
29+
// 오른쪽에서부터 최대차이
30+
for k in stride(from: n-2, through: 0, by: -1) {
31+
rightBest[k] = max(rightBest[k+1], maxRight - arr[k])
32+
maxRight = max(maxRight, arr[k])
33+
}
34+
35+
var answer = Int.min
36+
37+
for t in 0..<(n-1) {
38+
guard leftBest[t] != Int.min, rightBest[t+1] != Int.min else { continue }
39+
answer = max(leftBest[t] + rightBest[t+1], answer)
40+
}
41+
42+
print(answer)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# [Gold IV] A[j]-A[i]+A[l]-A[k] - 15487
2+
3+
[문제 링크](https://www.acmicpc.net/problem/15487)
4+
5+
### 성능 요약
6+
7+
메모리: 143620 KB, 시간: 432 ms
8+
9+
### 분류
10+
11+
다이나믹 프로그래밍
12+
13+
### 제출 일자
14+
15+
2026년 1월 12일 14:46:29
16+
17+
### 문제 설명
18+
19+
<p>크기가 N인 배열 A가 주어졌을 때, i < j < k < l을 만족하는 (i, j, k, l) 중에서 A[j]-A[i]+A[l]-A[k]의 최댓값을 구하는 프로그램을 작성하시오. </p>
20+
21+
### 입력
22+
23+
<p>첫째 줄에 배열 A의 크기 N(4 ≤ N ≤ 1,000,000)이 주어진다.</p>
24+
25+
<p>둘째 줄에는 배열 A에 들어있는 수가 순서대로 주어진다. 배열에 들어있는 수는 1,000,000보다 작거나 같은 자연수이다.</p>
26+
27+
### 출력
28+
29+
<p>첫째 줄에 i < j < k < l을 만족하는 (i, j, k, l) 중에서 A[j]-A[i]+A[l]-A[k]의 최댓값을 출력한다.</p>
30+

0 commit comments

Comments
 (0)