Smallest subarray with sum greater than a given value

Given an array of integers and a number x, find the smallest subarray with sum greater than the given value.

input: a = {1,4,45,6,0,19}

 x = 510 

output: 3

input: a1 = {1,10,5,2,7}

x1 = 9

output:1

intput: a2= {1,11,100,1,0,200,3,2,1,250}

x2 = 280

output: 4


设置start和end指针,从数组第一个元素开始累加,累加后与x值进行比较,若大于x,则从队列尾端减去一个值后再做比较,如果小于x则继续往后累加。当end指针大于数组长度时,报错,没有正确答案。每次获得大于x的值时,都与当前存下的长度值做比较,如果小于则替换。

package p_3;

public class Main {
	public static void main(String args[])
	{
		int[] a = {1,4,45,6,0,19};
		int x = 510;
		int number = a.length;
		int[] a1 = {1,10,5,2,7};
		int x1 = 9;
		int number1 = a1.length;
		int[] a2= {1,11,100,1,0,200,3,2,1,250};
		int x2 = 280;
		int number2 = a2.length;
		int xxx = sum(a,x,number);
		if(xxx == -100)
		{
			System.out.println("No possilbe");
		}
		else
		{
			System.out.println(xxx);
		}
		xxx = sum(a1,x1,number1);
		if(xxx == -100)
		{
			System.out.println("No possilbe");
		}
		else
		{
			System.out.println(xxx);
		}
		xxx = sum(a2,x2,number2);
		if(xxx == -100)
		{
			System.out.println("No possilbe");
		}
		else
		{
			System.out.println(xxx);
		}
	}
	public static int sum(int[] a,int x,int number)
	{
		int current_number = 999;
		int start = 0;
		int end = 1;
		int total = a[0];
		while(end<number)
		{
			if(total<=x)
			{
				total = total+a[end];
				end++;
			}else{				
				int temp_number = end - start;
				if(temp_number<current_number)
				{
					current_number = temp_number;
				}
				total = total - a[start];
				start ++;
			}
		}
		if(current_number == 999)
			return -100;
		else
			return current_number;
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值