一道Google算法题:给一个长度为2N的非负整数数组arr。现在每次删除最左端或最右端的元素,重复N次为止。请返回被删掉的数字之和最大是多少。

题目链接:https://www.nowcoder.com/discuss/205633?type=2&order=3&pos=184&page=1
题目来源:牛客网

题目描述

2、给一个长度为2N的非负整数数组arr。现在每次删除最左端或最右端的元素,重复N次为止。请返回被删掉的数字之和最大是多少。

例:

  • [1,2,3,4] => 4 + 3 = 7
  • [1,100,2,8] => 1 + 100 = 101
  • [98, 52, 67, 89]=> 98+89 = 187

解题思路:滑动窗口

学过计算机网络的人应该都知道有滑动窗口这个概念。这里设置一个长度为N的滑动窗口,假设有 [a, b, c, d, e, f , g, h,i]。算法步骤如下:

  • 1、滑动窗口取左区间,滑动窗口的内容为[a, b, c, d],作如下计算:
max=a+b+c+d;
tmp = max;
  • 2、滑动窗口移动一个位置,此时滑动窗口的内容为[i, a, b, c], 作如下判断:
tmp = tmp - d + i;
if tmp > max:
	max = tmp
  • 3、重复步骤2,直至滑动窗口为[f, g, h, i], 此时的max是解。

上述算法的滑动窗口变化如下:

1、[a, b, c, d]
2、[i, a, b, c]
3、[h, i, a, b]
4、[g, h, i, a]
5、[e, f, g, h]

求出每个滑动窗口的值,取最大值就是这题的解。

算法实现

#include<stdio.h>

unsigned long long slide_window(const int *arr, unsigned int size)
{
	unsigned int half = size / 2;
	unsigned int i, j;
	unsigned long long max, tmp;
	max = 0;
	tmp = 0;
	for (i = 0; i < half; i++)
	{
		// here, variable max may overflow in real produce environment.
		max += (unsigned long long)arr[i];
	}
	tmp = max;
	for (j = 0; j < half; j++)
	{
		i--;
		// here, variable tmp may overflow in real produce environment.
		tmp = tmp - (unsigned long long)arr[i] + (unsigned long long)arr[size-j-1];
		if (tmp > max)
		{
			max = tmp;
		}	
	}
	return max;
}

int main()
{
	unsigned int arr[] = {4, 9, 130, 21, 10, 2, 100, 33, 1, 3};
	unsigned long long result = 0;
	result = slide_window(arr, sizeof(arr)/sizeof(unsigned int));
	printf("result is: %lld", result);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值