zoukankan      html  css  js  c++  java
  • [CareerCup][Google Interview] Given two arrays A & B of length l

    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.

  • 相关阅读:
    arcgis中根据坐标文件生成要素类
    论C#及.net缺点及发展
    测绘类投稿指南
    .NET 4.0 Beta2中的BigInteger和Complex类(转)
    沈阳招聘.NET(C#)高级软件工程师
    测树学weibull拟合matlab程序,难者不会,会者不难
    景观生态专用软件
    使用匿名函数在后台线程中设置窗体控件属性 ()转
    matlab如何统计矩阵各元素的出现次数
    科学计算与开发环境
  • 原文地址:https://www.cnblogs.com/chkkch/p/2761609.html
Copyright © 2011-2022 走看看