leetcode 1218. Longest Arithmetic Subsequence of Given Difference(给定差值的最长算术子序列)

MOS管热阻的测量方法 实验室内如何测试mos管热阻 阅读详情

在这里插入图片描述

给数组arr和一个差值difference, 不打乱arr中数字的顺序,抽取最长的子序列,使序列中每相邻两个元素的差值为difference.
求满足条件的最长子序列的长度。

思路:

DP

因为差值difference是固定的,每抽取一个元素,它前面的元素也是固定的。
比如现在的元素为arr[ i ], 那么它前面的元素一定是arr[ i ] - difference.
所以到arr[ i ]为止的序列长度也是固定的。

只需要统计到arr[ i ]为止的子序列长度。
记下这些长度的最大值。

dp数组可以用一个hashMap, 保存(arr[ i ], 到arr[ i ]为止的子序列长度),
也可以用数组。

(1)HashMap

    public int longestSubsequence(int[] arr, int difference) {
        Map<Integer,Integer> dp = new HashMap<>();
        int n = arr.length;
        int res = 0;

        for(int i = 0; i < n; i++) {
            dp.put(arr[i], dp.getOrDefault(arr[i]-difference, 0)+1);
            res = Math.max(res, dp.get(arr[i]));
        }

        return res;
    }

(2) 数组
直接下标取元素,速度更快,
为了节省存储空间,dp数组长度为arr的最大值-最小值+1.
但是要注意dp中的下标是arr[ i ] - min. 并不是arr的下标 i。

    public int longestSubsequence(int[] arr, int difference) {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int res = 1;

        for(int num : arr) {
            min = Math.min(min, num);
            max = Math.max(max, num);
        }

        int[] dp = new int[max-min+1];
        for(int i = 0; i < arr.length; i++) {
            int cur = arr[i] - min;
            int pre = cur - difference;
            if(pre >= 0 && pre < dp.length) {
                dp[cur] = dp[pre] + 1;
                if(dp[cur] > res) res = dp[cur];
            } else {
                dp[cur] = 1;
            }
        }
        return res;
    }
华为OD机试真题2025双机位C卷 C++ 实现【卡牌游戏】 小明正在尝试一种新的牌游戏。游戏规则只如下:首先,小明拿到一张写有数字m的牌。 然后,他会拿到另外n张牌,上面分别写有不同的数字,牌排成一排。小明的目标是从这排牌中找到一串连续的牌,这些牌上数字的总和可以被 m整除。你的任务是判断小明是否可以完成这个目标。 阅读详情

相关推荐

hi3516cv610在PQStream上实现拉出图像,windows和板端操作记录

PQStream拉出图像

weixin_51838255的博客 734

LeetCode 1218. Longest Arithmetic Subsequence of Given Difference

[Med] LeetCode 1218. Longest Arithmetic Subsequence of Given Difference 链接: https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/ 题目描述: Given an integer array arr and an i...

MrJustin的博客 367

Ubuntu 20.04 系统备份和还原

最近大家Ubuntu开发环境,经常出现搭着搭着系统就挂了,于是开始琢磨了Ubuntu系统的备份和还原,以备不时之需,Linux环境搭建实在是有点太细,好多情况下,就算曾经搭建过一遍,再次搭建有些包还是忘了安装,做好备份是十分必要的。 经过了一番研究,Ubuntu备份有很多方式:根目录tar、dd、Systemback(1.0版本已经不维护了,2.0版本收费)等等,最终决定使用 —— Timesift, 因为方便一些。 文章参考:小马虎的救星——Timeshift Timeshift Timeshift,是L

Z_Paper的博客 2万+

Leetcode 1218.最长定差子序列(Longest Arithmetic Subsequence of Given Difference)

Leetcode 1218.最长定差子序列 1 题目描述(Leetcode题目链接)   给你一个整数数组 arr 和一个整数 difference,请你找出 arr 中所有相邻元素之间的差等于给定 difference 的等差子序列,并返回其中最长的等差子序列的长度。 输入:arr = [1,2,3,4], difference = 1 输出:4 解释:最长的等差子序列是 [1,2,3,4]。 ...

qq_39378221的博客 598

从零开始做对容量规划:一文讲透 SAP Greenfield sizing 与 Quick Sizer 落地方法

摘要 SAP项目早期硬件规划面临业务细节缺失的挑战,Greenfield sizing方法通过Quick Sizer工具将业务需求转化为硬件资源需求。该方法聚焦主要负载驱动因素而非精确预测,采用标准化问卷形式输入并发用户数、业务处理量等参数,输出内存、CPU等资源需求。关键步骤包括选择正确的Quick Sizer版本、创建sizing项目、参考SAP基准测试和认证目录校准结果,最终将需求交由硬件厂商落地。该方法特别适用于缺乏历史数据的新系统部署,帮助在不确定性中建立可控的容量规划模型,避免资源浪费或性能不足

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 223

图解电动汽车:电动汽车的分类

前面《电动汽车简介》中简单介绍了电动汽车的分类,主要包括混合动力电动汽车(HEV)和纯电动汽车(BEV)两大类。其中,混合动力汽车又可分为非插电式混合动力汽车、插电式混合动力汽车(PHEV)以及增程式电动汽车(REEV)。 主要分类 简单来说,各类电动汽车的特点如下。 纯电动汽车(BEV)就是指动力来源完全由电能提供,由电动机驱动的汽车,并且电能储存在电池中。 混合动力汽车(HEV)则是指动力来源可以是化石燃料,也可以是电能,并且电能除了可以存储在电池中,还可以由化石能源转化而来。 非插电式混合动力汽车

程序员「阿基米东」的编程之旅 3111

[leetcode] 1218. Longest Arithmetic Subsequence of Given Difference

Description Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference. Example 1: Input:

Learning from the mistakes 242

ESP32设备驱动-VCNL4040趋近传感器

VCNL4040 将趋近传感器 (PS)、环境光传感器 (ALS) 和高功率 IRED 集成到一个小型封装中。它通过CMOS工艺将光电二极管、放大器和模数转换电路集成到一个芯片中。

视觉与物联智能 949

leetcode 1218. Longest Arithmetic Subsequence of Given Difference 解法 python

一.问题描述 Given an integer arrayarrand an integerdifference, return the length of the longest subsequence inarrwhich is an arithmetic sequence such that the difference between adjacent elements in ...

CSerwangjun的博客 584

DFI协议时序

参数名称典型值应用场景关键影响tcmd_lat1-2个时钟周期命令与地址锁存同步地址错误风险tphy_wrlat1-2个时钟周期写操作响应速度写带宽与延迟2-3个时钟周期写操作端到端延迟系统吞吐量1-2个时钟周期连续写命令间隔信号干扰与资源冲突tphy_rdlat1-2个时钟周期读操作响应速度读带宽与延迟trddata_en由CL决定(如0.41 ns)读数据返回时间系统延迟10-20 ps写数据与命令对齐数据丢失风险<1 µs低功耗模式切换。

qq_43134430的博客 5118

github中文汉化插件安装教程

本章教程,主要介绍如何汉化github网页,有部分小伙伴阅读英文版的网页可能比较吃力,想汉化一下页面,在网上收集了一些资料,总结了一下当前可用的汉化教程。

猿小白的博客 3532

【LeetCode】1218. Longest Arithmetic Subsequence of Given Difference

Given an integer array arrand an integer difference, return the length of the longest subsequence in arrwhich is an arithmetic sequence such that the difference between adjacent elements in the subs...

韩旭051的博客 635

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

LeetCode 1218. Longest Arithmetic Subsequence of Given Difference 题解

查阅更多的题解,请点击 GitHub传送门 Problem 1218. Longest Arithmetic Subsequence of Given Difference Solution DP, O(n) time 題目是求最长的等差序列,利用dp求解,假设前i个数我们已经得到解,那么加入第i+1个数x,若x-difference在前i个数中存在,那么更新之前候选序列;若不存在,x可以作为一个...

彼得.攀的blog 446

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

1218. Longest Arithmetic Subsequence of Given Difference

https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/ Given an integer arrayarrand an integerdifference, return the length of the longest subsequence inarrwhich is an arithmetic sequence such that the difference between ad...

Young's Blog 162

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

【LeetCode 1218】 Longest Arithmetic Subsequence of Given Difference

题目描述 Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the...

iCode_girl的博客 259

leetcode - 1218. Longest Arithmetic Subsequence of Given Difference

leetcode - 1218

sinat_41679123的博客 403

【Leetcode】1218. Longest Arithmetic Subsequence of Given Difference

题目地址: https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/ 给定一个长nnn数组AAA,和一个数ddd,问AAA中以ddd为公差的等差子序列的最长长度。 设f[x]f[x]f[x]为以xxx结尾的最长等差子序列的最长长度(可以将fff视为一个哈希表)。在遍历AAA的时候时刻维护A[0:i]A[0:i]A[0:i]这个区间的fff对应的信息。当遍历到A[i]A[i]A[i]的时候,A[0:i−1

数学、算法爱好者的博客 575

LeetCode 1218. Longest Arithmetic Subsequence of Given Difference【哈希表,动态规划】中等

本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,还会用多种编程语言实现题解,涉及到通用解法时更将归纳总结出相应的算法模板。。

memcpy0的博客 686

LeetCode 1218. Longest Arithmetic Subsequence of Given Difference【动态规划,哈希表,贪心】中等

本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,还会用多种编程语言实现题解,涉及到通用解法时更将归纳总结出相应的算法模板。 为了方便在PC上运行调试、分享代码文件,我还建立了相关的仓库:https://github.com/memcpy0/LeetCode-Conqu.

memcpy0的博客 447

LeetCode——1218. 最长定差子序列(Longest Arithmetic Subsequence of Given Difference)[中等]——分析及代码(C++)

LeetCode——1218. 最长定差子序列[Longest Arithmetic Subsequence of Given Difference][中等]——分析及代码[C++]一、题目二、分析及代码1. 动态规划(1)思路(2)代码(3)结果三、其他 一、题目 给你一个整数数组 arr 和一个整数 difference,请你找出并返回 arr 中最长等差子序列的长度,该子序列中相邻元素之间的差等于 difference 。 子序列 是指在不改变其余元素顺序的情况

江南土豆的博客 331

leetcode 1218 Longest Arithmetic Subsequence of Given Difference(DP, 递增子序列)

题目大意: 找出一串序列中的最长等差序列 解题思路: 首先这道题是一道DP题,我们很容易联想到最长递增子序列的题,里面有nlogn和n^2的解法。显然nlogn的方法无法往这里迁移,因为里面用的是lower_bound而不是具有等差序列性质的。在这里我们可以修改n^2的解法来达到nlogn复杂度。在n^2算法里面,我们需要往前面扫描,找到比当前小的元素且lis需要最大,这使我们必须完整的扫完...

FrostMonarch的博客 297

leetcode 1218. Longest Arithmetic Subsequence of Given Difference 最长定差子序列-耗时99

Problem:耗时99%,根据提示用的动态规划,dp[i]是数字对应的符合条件的最大个数,dp[i] = dp[i-difference] + 1,只需要从前向后遍历的,然后求最大值,没有出现过的值都是0,dp[i] = max(dp[i-difference]+1, dp[i]);

邹九的个人博客 154

【DP】LeetCode - 1218. 最长等差数列子数组

  给一个已排序数组,问最长的等差数列子数组多长。这道题和 LIS 基本一模一样,LIS 可以参考 https://blog.csdn.net/Bob__yuan/article/details/99696806。 样例输入: 5 1 2 3 4 5 样例输出: 5   用一个二维 dp 矩阵,dp[i][d] 表示以 i 位置为结尾的,差为 d 的等差数列的长度。 #include &lt...

Bob__yuan的博客 596

Leetcode-1218. Longest Arithmetic Subsequence of Given Difference 最长定差子序列 (DP)

题目 给你一个整数数组 arr 和一个整数 difference,请你找出 arr 中所有相邻元素之间的差等于给定 difference 的等差子序列,并返回其中最长的等差子序列的长度。 链接:https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/ Given an integer array arr and an integer difference, return the length of

JamieLuo的博客 288

最长定差子序列

给你一个整数数组arr和一个整数difference,请你找出arr中所有相邻元素之间的差等于给定difference的等差子序列,并返回其中最长的等差子序列的长度。 示例 1: 输入:arr = [1,2,3,4], difference = 1 输出:4 解释:最长的等差子序列是 [1,2,3,4]。 示例2: 输入:arr = [1,3,5,7], differe...

weixin_41791402的博客 323

【动态规划】子序列问题(二)

【动态规划】子序列问题(二):446. 等差数列划分 II - 子序列、1027. 最长等差数列、873. 最长的斐波那契子序列的长度、1218. 最长定差子序列

tan_run的博客 823
上一篇: leetcode 1493. Longest Subarray of 1‘s After Deleting One Element(删除一个元素后‘1‘ 的最大长度)
下一篇: leetcode 445. Add Two Numbers II(两数相加)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址