난이도: Medium
문제 설명
You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.
The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.
Return the maximum score of a pair of sightseeing spots.
문제 예제
Example 1:
Input: values = [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
Example 2:
Input: values = [1,2]
Output: 2
제한 사항
- 2 <= values.length <= 5 * 10^4
- 1 <= values[i] <= 1000
✏️ Solution(솔루션)
class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
answer = 0
n = len(values)
dp = [0 for _ in range(n)]
dp[0] = values[0]
for i in range(1, n):
answer = max(answer, dp[i-1] + values[i] - i)
dp[i] = max(dp[i-1], values[i] + i)
return answer
문제에서는 values[i] + values[j] + i - j 라고 나와있지만, values[i] + i + values[j] - j로 볼 수도 있다.
따라서, dp 배열을 사용해 dp[i]에 values[i]+i 의 최대값을 저장하고, dp[i-1]값과 values[i]−i를 더해 answer변수와 비교해서 더큰 값을 answer에 저장했다.
그리고 answer를 return하여 정답을 맞출 수 있었다.
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 3286. Find a Safe Walk Through a Grid (Python) (0) | 2024.12.29 |
---|---|
[LeetCode] 1122. Relative Sort Array (Python) (1) | 2024.12.28 |
[LeetCode] 494. Target Sum (Python) (0) | 2024.12.26 |
[LeetCode] 1962. Remove Stones to Minimize the Total (Python) (2) | 2024.12.23 |
[LeetCode] 2337. Move Pieces to Obtain a String (Python) (1) | 2024.12.20 |