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.

  • 相关阅读:
    hdu2574 Hdu Girls' Day (分解质因数)
    python------logging模块
    python之异常
    python之反射
    python面向对象之封装
    python之面向对象2
    pyhton之路---面向对象
    python之路模块与包
    python常用模块
    匿名函数
  • 原文地址:https://www.cnblogs.com/chkkch/p/2761609.html
Copyright © 2011-2022 走看看