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.

  • 相关阅读:
    意外发现在调用Activator.CreateInstance的时候在构造函数处加断点居然可以~~
    手机操作系统
    读取Excel文件到DataSet
    支持mrp软件的手机(MTK手机)检测
    如何查看手机系统版本
    .NET进度条用例
    dos命令导出指定类型的文件列表
    FTP上传下载 FTP操作类 FTPHelper 异步上传 递归创建文件文件夹
    批量删除GridView(DataGrid)选中项
    sql判断临时表是否存在
  • 原文地址:https://www.cnblogs.com/chkkch/p/2761609.html
Copyright © 2011-2022 走看看