博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[CareerCup][Google Interview] Given two arrays A & B of length l
阅读量:7296 次
发布时间:2019-06-30

本文共 1696 字,大约阅读时间需要 5 分钟。

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.

转载地址:http://pxynm.baihongyu.com/

你可能感兴趣的文章
高考查分数微信就能搞定
查看>>
ORM简介
查看>>
so 问题来了,你现在值多少钱?
查看>>
17.3. mpstat
查看>>
dataguard中MRP无法启动的问题分析和解决
查看>>
Oracle 12C R2-新特性-转换函数的增强
查看>>
ITIL的一些简单感受
查看>>
使用oracheck进行系统巡检
查看>>
云计算+物联网的前景更加诱人
查看>>
SQL Server 中的事务与事务隔离级别以及如何理解脏读, 未提交读,不可重复读和幻读产生的过程和原因...
查看>>
购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(2)--前端,以及前后端Session
查看>>
HDOJ/HDU 2566 统计硬币(公式~遍历~)
查看>>
Java RMI(远程方法调用) 实例与分析 (转)
查看>>
架构漫谈(二):认识概念是理解架构的基础
查看>>
[20161219]关于LANGUAGE_MISMATCH.txt
查看>>
天使投资乱象频出 熟人元素何时剔除
查看>>
使用SQLCMD在SQLServer执行多个脚本
查看>>
如何使用通用Mapper
查看>>
快速安装及部署DRBD
查看>>
Java调试那点事
查看>>