#1477. Find Two Non-overlapping Sub-arrays Each With Target Sum

保姆级教程:用Python+OpenCV实现相移法与格雷码三维重建(从生成条纹到点云生成) 本文详细介绍了使用Python和OpenCV实现相移法与格雷码三维重建的全流程,从条纹生成到点云计算。通过结构光技术,结合相移法和格雷码,实现高精度的三维重建,适用于无纹理物体表面的密集对应点生成。教程包含环境搭建、条纹生成、相位计算、三维点云重建及常见问题排查,适合计算机视觉开发者和研究人员。 阅读详情

题目描述:

Given an array of integers arr and an integer target.

You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.

Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.

Example 1:

Input: arr = [3,2,2,4,3], target = 3
Output: 2
Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.

Example 2:

Input: arr = [7,3,4,7], target = 7
Output: 2
Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.

Example 3:

Input: arr = [4,3,2,6,2,3,4], target = 6
Output: -1
Explanation: We have only one sub-array of sum = 6.

Example 4:

Input: arr = [5,5,4,4,5], target = 3
Output: -1
Explanation: We cannot find a sub-array of sum = 3.

Example 5:

Input: arr = [3,1,1,1,5,1,2,1], target = 3
Output: 3
Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.

Constraints:

  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 1000
  • 1 <= target <= 10^8
class Solution {
public:
    int minSumOfLengths(vector<int>& arr, int target) {
        // 由于都是正数,一个起点最多对应一个终点,所有可能的子数组最多有n个
        // 也是由于都是正数才可以用滑动窗口
        int result = INT_MAX;
        const int n = arr.size();
        // min_length[i]表示在i和i之前的合法子数组的最小长度
        vector<int> min_lens(n, INT_MAX);
        int sum = 0;
        int i = 0, j = 0;
        int min_len = INT_MAX;
        while(j < n) {
            sum += arr[j];
            while(i <= j && sum > target) {
                sum -= arr[i];
                i++;
            }
            if (sum == target) {
                int cur_len = j - i + 1;
                min_len = min(min_len, cur_len);
                // 当发现当前合法子数组之前已经有了合法子数组,则更新结果
                if (i > 0 && min_lens[i - 1] != INT_MAX) {
                    result = min(result, cur_len + min_lens[i - 1]);
                }
            }
            // 最后再更新min_lens
            min_lens[j] = min_len;
            j++;
        }
        return result == INT_MAX ? -1 : result;
    }
};

 

基于Simulink/Matlab的VSG并网系统单相接地与相间短路故障仿真建模与特性分析 本文详细介绍了基于Simulink/Matlab搭建虚拟同步发电机(VSG)并网系统仿真模型的方法,并重点分析了单相接地与相间短路故障下的系统特性。通过设置三相故障模块参数,模拟了故障发生时的电压、电流变化及VSG动态响应,为理解故障机理、优化控制策略及设计继电保护提供了仿真依据与实践指导。 阅读详情

相关推荐

ptrade量化策略之沪深300指数增强

本策略的核心是在沪深300股票池中选股,选择的股票都是市值比较大,业绩比较好的白马股,根据市场相对位置以及基本面因子来选择股票

qq_29301281的博客 1190

LeetCode 1477. 找两个和为目标值且不重叠的子数组 每日一题

LeetCode 1477. 找两个和为目标值且不重叠的子数组 每日一题

lishifu_的博客 2512

经典蓝牙中的Sniff、Hold与Park模式

若主设备在Sniff Attempt窗口外发送数据,从设备无法接收,需依赖重传机制。移动时立即传输数据。:Sniff Interval=20ms,Attempt=1时隙。:传感器每2秒唤醒一次同步信标,主设备按需唤醒特定传感器采集数据。Slave进入Sniff模式:每20ms唤醒1个时隙监听数据。:设备需要短暂执行高优先级任务(如扫描其他蓝牙设备)。:无数据传输超时后,设备可能自动进入Sniff模式。:主设备通过信标唤醒从设备,或从设备主动请求退出(:平衡功耗与响应速度,适合间歇性数据传输设备。

shishuangquan111的博客 1673

Find Two Non-overlapping Sub-arrays Each With Target Sum

Given an array of integersarrand an integertarget. You have to findtwo non-overlapping sub-arraysofarreach with sum equaltarget. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays ismini...

leetcode 解题思路 388

自监督预训练(三)wav2vec 2.0原理剖析

一、整体流程 二、feature encoder 理解Conv1d nn.Conv1d(in_channels=5, out_channels=20, kernel_size=3, stride=2) 假设输入input=(batch, in_channels, in_len) batch=1 in_channels=5,对应向量大小,比如word embedding in_len=10,对应word的个数 cnn内部kernel=(in_channels, kernel_size)=(5,3),相当

xmdxcsj的专栏 2万+

西电微机系统课程设计步进电机开环控制系统

** 微机系统与应用课程设计 课题二 步进电机开环控制系统设计** 一、程设计目的 掌握微机系统总线与各芯片管脚连接方法,提高接口扩展硬件电路的连接能力。 加深对 A/D 和并行接口芯片的工作方式和编程方法的理解。 搞懂步进电机的工作原理及控制方式,掌握开环控制系统的设计思路和实现方法。 二、课程设计的内容 手动调节电位器旋钮(0V~5V),通过 ADC0809 模拟输入水库水位 0 米~50...

qq_37015775的博客 4033

1477. 找两个和为目标值且不重叠的子数组

1477. 找两个和为目标值且不重叠的子数组题目描述 :样例1:样例2:样例3:样例4:示例 5:提示:解题思路:代码实现: 题目描述 : 给你一个整数数组 arr 和一个整数值 target 。 请你在 arr 中找 两个互不重叠的子数组 且它们的和都等于 target 。可能会有多种方案,请你返回满足要求的两个子数组长度和的 最小值 。 请返回满足要求的最小长度和,如果无法找到这样的两个子数组,请返回 -1 。 样例1: 输入:arr = [3,2,2,4,3], target = 3 输出:2 解释:

u010155337的博客 549

Homebrew高效升级与国内镜像源配置全攻略

本文详细介绍了如何通过配置国内镜像源(如清华、中科大、阿里云)来高效升级Homebrew,解决国内开发者访问GitHub仓库速度慢的问题。文章提供了从基础配置到永久生效的完整教程,包括常见问题解决和进阶技巧,帮助开发者大幅提升软件包管理效率。

weixin_28835551的博客 416

[leetcode] 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum

Description Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arr

Learning from the mistakes 350

基于ENVI完成影像的去云操作以及后续处理

利用ENVI完成重采样影像的去云操作 由于SNAP重采样之后的影像是分波段保存的,ENVI的波段运算工具一次也只能输出一个波段,所以去云的操作分波段进行,原理是掩膜法 下面是打开所有波段后的界面 去云的依据是以quality_scene_classification栅格文件为基础,该文件是哨兵2数据自带的场景质量分类图,包含12个级别,可以通过SNAP软件查看,如下图所示: 对于去云操作而言,我们只需要DARK_FEATURE_SHADOW(地形等),CLOUD_SHADOW(云阴影)、CL

lemon_tttea的博客 2万+

基于YOLOv11的工业零件表面缺陷检测系统:从原理到实现

工业质量控制是制造业的核心环节,表面缺陷检测作为其中重要组成部分,直接关系到产品质量和企业效益。本文详细介绍了一种基于YOLOv11深度学习算法的工业零件表面缺陷检测系统,包含完整的算法原理分析、数据集构建方法、模型训练策略以及用户界面设计。通过大量实验验证,该系统能够高效准确地检测零件表面的划痕、凹陷、锈蚀等多种缺陷,检测精度达到96.2%,满足工业实时检测需求。本文还提供了完整的代码实现和详细的技术文档,为相关领域的研究者和工程师提供参考。关键词:表面缺陷检测;YOLOv11;深度学习;工业视觉;

YOLO 566

Leetcode 689. Maximum Sum of 3 Non-Overlapping Subarrays

Problem: In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. Each subarray will be of size k, and we want to maximize the sum of all 3*k entries. Retu...

weixin_34327223的博客 165

Android Binder的两三事--基于Android14源码

Android14-Framework-Binder

保持专注,保持热爱 1140

1031. Maximum Sum of Two Non-Overlapping Subarrays

1、题目 Given an arrayAof non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengthsLandM. (For clarification, theL-length subarra...

Smartershining的博客 294

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

LeetCode 题目讲解集合

LeetCode 题目集合 题号 难度 正文 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...

MrJustin的博客 331

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode 1031. Maximum Sum of Two Non-Overlapping Subarrays

链接:https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/ 思路 假设L子串在M子串左边。反向迭代A,到达位置i时,计算M子串[i, i+M)总和,并记录到i时已计算的M子串总和的最大值maxMSum[i]。然后正向迭代A,到达位置i时,此时已知的两串总和最大为maximal,计算L子串[i, i+L...

zjj1149的博客 468

力扣 第28场双周赛第3题(滑动窗口) 找两个和为目标值且不重叠的子数组

参考题解出处:ikaruga 思路 使用滑动窗口找出所有和为 target 的子数组 使用 multimap 按照长度保存 使用双循环依次遍历两个不同的子数组 如果有交叉跳过,注意是按长度排的,要在前在后都判断 记录最小值 剪枝 class Solution { public: int minSumOfLengths(vector<int>& arr, int target) { multimap<int,int> mp; in..

一粒大榴莲的博客 322

证明精确的4SAT是NP_完全问题

题目描述: 在精确的4SAT(EXACT 4SAT)问题中,输入为一组子句,每个子句都是恰好4个文字的析取,且每个变量最多在每个子句中出现一次。目标是求它的满足赋值——如果该赋值存在。证明精确的4SAT是NP_完全问题。 显然,4SAT问题是NP问题,所有可能的赋值总数的指数级的。现从3SAT归约到4SAT来证明4SAT为NP_完全问题: 给定3SAT的实例,对I中的任意子句(a1∨

LawFile的博客 1685

LeetCode #22 - Generate Parentheses

题目描述: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()",

LawFile的博客 596

LeetCode #19 - Remove Nth Node From End of List

题目描述:   Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1-&gt;2-&gt;3-&gt;4-&gt;5, and n = 2. After removing the second n...

LawFile的博客 519

LeetCode #21 - Merge Two Sorted Lists

题目描述: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 此题可以直接模拟归并排序的步骤,但是要小心指针为空的情况。 /** * Defini

LawFile的博客 498

LeetCode #25 - Reverse Nodes in k-Group

题目描述: Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If t

LawFile的博客 438

LeetCode #23 - Merge k Sorted Lists

题目描述: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity 这道题可以利用mergeTwoLists来做,一种方法是将k个链表一个一个地归并,即需要k步。随着归并的次数越多,已经归并的链表会越来越长,所以效率比较差。在这道题的最后一个测试案例中

LawFile的博客 410

#752. Open the Lock

题目描述: You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots:'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn'9'to be'0', or'0'to be'9'. Each move consi...

LawFile的博客 404

LeetCode #91 - Decode Ways

题目描述: A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the tot

LawFile的博客 381

LeetCode #105 - Construct Binary Tree from Preorder and Inorder Traversal

题目描述: Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 根据前序遍历和中序遍历构造二叉树。还是利用递归来解决,前序遍历的第一个元素即为二叉树的根节点

LawFile的博客 380

#1423. Maximum Points You Can Obtain from Cards

题目描述: There are several cardsarranged in a row, and each card has an associated number of pointsThe points are given in the integer arraycardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exa...

LawFile的博客 378
上一篇: #1423. Maximum Points You Can Obtain from Cards
LawFile
博客等级 码龄10年 5粉丝 627原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值