엔지니어 게시판
LeetCode 솔루션 분류

1027. Longest Arithmetic Subsequence

컨텐츠 정보

본문

https://leetcode.com/problems/longest-arithmetic-subsequence/


Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.

Recall that a subsequence of an array nums is a list nums[i1], nums[i2], ..., nums[ik] with 0 <= i1 < i2 < ... < ik <= nums.length - 1, and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).

 

Example 1:

Input: nums = [3,6,9,12]
Output: 4
Explanation: 
The whole array is an arithmetic sequence with steps of length = 3.

Example 2:

Input: nums = [9,4,7,2,10]
Output: 3
Explanation: 
The longest arithmetic subsequence is [4,7,10].

Example 3:

Input: nums = [20,1,15,3,10,5,8]
Output: 4
Explanation: 
The longest arithmetic subsequence is [20,15,10,5].

 

Constraints:

  • 2 <= nums.length <= 1000
  • 0 <= nums[i] <= 500


 

관련자료

댓글 1

Coffee님의 댓글

  • 익명
  • 작성일
class Solution {
    public int longestArithSeqLength(int[] nums) {
        
        
        int[][] dp = new int[1001][1001];
        
        int n = nums.length;
        int maxLength = 1;
        // 3 6 9 12
        for(int i=1; i<n; i++){
            for(int j=0; j<i; j++){
                int diff = nums[i] - nums[j] + 500; // 500 is a complement from input
                dp[i][diff] = Math.max(dp[i][diff], dp[j][diff] + 1);
                maxLength = Math.max(maxLength, dp[i][diff]);
            }
        }
        
        return maxLength + 1;
    }
}
전체 396 / 9 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 202 명
  • 오늘 방문자 3,524 명
  • 어제 방문자 5,697 명
  • 최대 방문자 11,134 명
  • 전체 회원수 1,094 명
알림 0