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.

  • 相关阅读:
    spring boot.定时任务问题记录(TaskScheduler/ScheduledExecutorService异常)
    网站配置https(腾讯云域名操作)
    Java web如何定位工程路径
    centos7安装nginx
    个人博客搭建----基于solo
    velocity学习总结
    第四篇:用IntelliJ IDEA 搭建基于jersey的RESTful api
    Python 包批量升级
    Linux 常用命令更新汇总
    ubuntu 18.04 +firefox + selenium + python
  • 原文地址:https://www.cnblogs.com/chkkch/p/2761609.html
Copyright © 2011-2022 走看看