[CareerCup][Google Interview] Given two arrays A & B of length l

本文讨论了如何在两个非负整数数组中找到一个起始索引,使得从该索引开始进行特定差值求和操作时,整个过程中差值之和始终非负。通过将问题转化为寻找最大连续子序列和,采用反向遍历方法在O(n)时间内解决。解释了算法思路及证明过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two arrays A & B of length l, containing non negative integers, such that the sum of integers in A is the same as sum of integers in B.( The numbers need not be the same in both the arrays.)

Now if you start with an index 'k' in each array and do the following summation, SUMMATION (Ak-Bk), where Ak is the value at index k of array A, and Bk is the value at index k of array B, where 'k' increments and wraps back all the way to k-1, the final sum value will be zero.

Question: Find a suitable 'k' such that during any point in the summation, SUMMATION(Ak-Bk) is always non negative. Find such a 'k' in O(n) time.

 

最终,可以化简为找最大连续子序列和。证明真是无比精彩。

Suppose the array d contains the n differences i.e. d[i] = a[i] - b[i]. For the below d[i..j] detones the sum of elements in d from index i to j inclusive.

Without loss of generality assume d[n] > 0. There has to be one such d[n]. Otherwise all values are 0 and every index is a solution.

Starting from d[n] go backwards to find the max sum sequence that includes d[n]. This means going back as long as the running sum is positive while keeping track of the max sum. This is O(n). Suppose d[i..n] is the max sum. d[n] > 0 implies d[i..n] > 0.

The index i is our solution i.e. starting index such that all cumulative sums are >= 0.

Proof:

For all i <= j <= n, d[i..j] >= 0 :
If d[i..j] < 0 then d[i..n] = d[i..j] + d[j+1..n] < d[j+1..n]. This violates the premise that d[i..n] is the max sum.

For all j < i, d[i..n] + d[1..j] >= 0 :
If d[i..n] + d[1..j] < 0 then 0 = d[1..n] = d[i..n] + d[1..j] + d[j+1..i-1] and so d[j+1..i-1] > 0. This means d[j+1..i-1] + d[i..n] = d[j+1..n] > d[i..n]. Once again the premise that d[i..n] is max sum is violated.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值