【구간dp】A012LC_두 하위 서열의 최대 점적 (분류 토론)
1. Problem
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not). Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
2. 솔루션
방법1:dp
두 시퀀스 별칭 A, B
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
방법1:dp
두 시퀀스 별칭 A, B
dp[i][j] = A[i] × B[j]
, A, B의 현재 두 개만 선택하고 다른 개수는 선택하지 않음dp[i][j] = max(dp[i][j], dp[i-1][j])
, B의 제jj개수dp[i][j] = max(dp[i][j], dp[i][j-1])
, A의 ii 개수만 선택dp[i][j] = max(dp[i][j], dp[i-1][j-1] + A[i] × B[j])
에서 A, B의 현재 두 수와 앞에서 선택한 수로 구성된 가장 긴 점적과를 선택한다.class Solution {
public int maxDotProduct(int[] A, int[] B) {
int n1 = A.length, n2 = B.length, INF = -0x3f3f3f3f, f[][] = new int[n1+1][n2+1];
for (int i = 0; i <= n1; i++)
for (int j = 0; j <= n2; j++)
f[i][j] = INF;
for (int i = 1 ; i <= n1; i++)
for (int j = 1 ; j <= n2; j++) {
int pro = A[i-1] * B[j-1];
f[i][j] = pro;
f[i][j] = Math.max(f[i][j], f[i][j-1]);
f[i][j] = Math.max(f[i][j], f[i-1][j]);
f[i][j] = Math.max(f[i][j], f[i-1][j-1] + pro);
}
return f[n1][n2];
}
}
복잡도 분석
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Rails Turbolinks를 페이지 단위로 비활성화하는 방법원래 Turobolinks란? Turbolinks는 링크를 생성하는 요소인 a 요소의 클릭을 후크로 하고, 이동한 페이지를 Ajax에서 가져옵니다. 그 후, 취득 페이지의 데이터가 천이 전의 페이지와 동일한 것이 있...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.