Smallest Subarray with a given sum

本文介绍如何使用O(n)时间复杂度和O(1)空间复杂度的算法解决Smallest Subarray with a Given Sum问题,通过滑动窗口技巧找出数组中和至少为给定值S的最小子连续子数组的长度。实例分析了输入数组[2,1,5,2,3,2]和S=7的情况。
摘要由CSDN通过智能技术生成

Smallest Subarray with a given sum

Problem Statement

Given an array of positive numbers and a positive number ‘S’, find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0, if no such subarray exists.

Example

Input: [2, 1, 5, 2, 3, 2], S=7 
Output: 2
Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].

Input: [2, 1, 5, 2, 8], S=7 
Output: 1
Explanation: The smallest subarray with a sum greater than or equal to '7' is [8].

Solution

public static int getminnum(int a[],int num){
		
		if(a==null||a.length==0){
			return 0;
		}
		int sum = 0;
		int windowstart = 0;
		int min = Integer.MAX_VALUE;
		for ( int windowend =0;windowend<a.length;windowend++){
			sum+=a[windowend];
			while(sum>=num){
				min= Math.min(min,windowend- windowstart + 1);
				sum -= a[windowstart];
				windowstart++;
			}
		}
		return min;
	}

时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Jonathan is fighting against DIO's Vampire minions. There are n of them with strengths a1,a2,…,an. Denote (l,r) as the group consisting of the vampires with indices from l to r. Jonathan realizes that the strength of any such group is in its weakest link, that is, the bitwise AND. More formally, the strength level of the group (l,r) is defined as f(l,r)=al&al+1&al+2&…&ar. Here, & denotes the bitwise AND operation. Because Jonathan would like to defeat the vampire minions fast, he will divide the vampires into contiguous groups, such that each vampire is in exactly one group, and the sum of strengths of the groups is minimized. Among all ways to divide the vampires, he would like to find the way with the maximum number of groups. Given the strengths of each of the n vampires, find the maximum number of groups among all possible ways to divide the vampires with the smallest sum of strengths. Input The first line contains a single integer t (1≤t≤104) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer n (1≤n≤2⋅105) — the number of vampires. The second line of each test case contains n integers a1,a2,…,an (0≤ai≤109) — the individual strength of each vampire. The sum of n over all test cases does not exceed 2⋅105. Output For each test case, output a single integer — the maximum number of groups among all possible ways to divide the vampires with the smallest sum of strengths.c++实现
最新发布
07-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值