• [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.

  • 相关阅读:
    整理SVN代码-->正式环境的代码
    业务(1)
    在一个项目中跨领域调用接口的的实现
    一个java文件编译之后会产生多个class文件
    shutil模块
    shevle模块
    confiparser模块
    sys模块
    subprocess模块
    【ADO.NET】3、从TXT中导入数据到数据库
  • 原文地址:https://www.cnblogs.com/chkkch/p/2761609.html
Copyright © 2020-2023  润新知