lintcode 46

https://www.lintcode.com/contest/46/

  1. Longest Sequence
    Description
    Given an array a containing n positive integers, you can arbitrarily select a number of numbers to form an arithmetic progression, what is the maximum length of the arithmetic progression that can be composed?

The length of the array does not exceed 5000
Guarantee that a[i]a[i] is different from each other
a[i] <= 1e9a[i]<=1e9
Have you met this question in a real interview?
Example
Given a = [1,2,5,9,10],,return 3.

Explanation:
You can select [1, 5, 9] to form an arithmetic progression. The length of this is the longest, which is 3
Given a = [1,3],return 2.

Explanation:
At this time, only the series [1, 3] can be selected to form an arithmetic progression with the length of 2

2层循环+Set,Python TLE,Java MLE(我艹)
优化成Set数组形式,还是Python TLE,Java MLE(我艹)
https://www.geeksforgeeks.org/length-of-the-longest-arithmatic-progression-in-a-sorted-array/,居然这么tricky,服了
dp[i][j]表示前面2位为a[i],a[j]的最长AP,然后从后往前计算就可以利用dp数组减小计算量了

package lint5;

import java.util.Arrays;

public class Solution {

    public int getAnswer(int[] a) {
        // Write your code here
        if(a.length==0 || a.length==1) return a.length;
        
        int max=2;
        Arrays.sort(a);
        // dp[i][j]表示前面2位为a[i],a[j]的最长AP
        int[][]dp=new int[a.length][a.length];
        for(int i=0;i<a.length;i++) dp[i][a.length-1]=2;
        
        // 外层循环第二个数
        for(int j=a.length-2;j>=1;j--) {
            int i=j-1, k=j+1;
            // 内层循环第一个数,用i,k 2个循环变量
            while(i>=0 && k<=a.length-1) {
                if(a[i]+a[k]<2*a[j]) {
                    // dp[i][j]可能还有更优值,所以i不减
                    k++;
                } else if (a[i]+a[k]>2*a[j]) {
                    dp[i][j] = 2;
                    i--;
                } else {
                    dp[i][j] = dp[j][k]+1;
                    max = Math.max(max, dp[i][j]);
                    i--;
                    k++;
                }
            }
            
            // 可能是由于k跳出的循环,还需要求出剩下的i
            while(i>=0) {
                dp[i][j]=2;
                i--;
            }
        }
        
        return max;
    }
}

许久没刷题了,感觉校招要崩,一直在用Python,刷题老是TLE,FUCK

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,160评论 0 10
  • 29 是日心卦 每日抽一卦,就像每天照照镜子, 看看当下的心浮现了什么 震上天下雷天大壮 乌云盖顶,电闪雷鸣,路上...
    杨梵妮阅读 1,943评论 0 0
  • 看了菲儿老师画香水瓶的线稿,老师画的好仔细^O^一点点矫正,一点点修改,一点点完善o>_<o受益匪浅,自愧不如...
    小q33阅读 1,716评论 5 1
  • 养育孩子是一个逐步放手的过程,父母需要得体地退出。怎样做到得体?在孩子练习做自己领地主人的时候,守在一旁陪伴和支持...
    慕孜阅读 2,642评论 0 0