GERGOVIA -Wine trading in Gergovia
Pattern: Candy and assign cookies
Houses on a street each want to buy (positive) or sell (negative) wine, and the totals balance. Moving one bottle between neighbours costs 1. Whatever is bought on the left of a gap but not sold there must cross that gap, so the least work is the sum of |running total| over the gaps.
The problem
House i wants to buy a[i] bottles if positive, or sell -a[i] if negative; the values add up to 0. Carrying one
bottle from a house to its neighbour is one unit of work. Return the least total work. [5, -4, 1, -3, 1] gives 9.
The SPOJ version reads several streets; here each call is one street.
Think first
- Consider the gap between house i and i + 1. How much wine must cross it?
- Does the direction matter for the cost?
- Can any trade avoid crossing gaps it has to cross?
Hints
Brute force, and why it fails
Match every buyer with sellers and add amount × distance, trying every matching: exponential. Matching nearest-first works but is longer to write.
The key insight
The amount that must cross each gap is fixed by the running total, and passing wine along the street meets that bound exactly.
Dry run
| carry | 5 1 2 -1 |
|---|
a = [5, -4, 1, -3, 1]. Running totals after each house: 5, 1, 2, -1.
The plan
carry = 0; work = 0
for i in 0..n-2: carry += a[i]; work += |carry|
Complexity
- Time
O(n)- Space
O(1)
One pass.
Edge cases
- Two houses: |a[0]|.
- Already balanced pairs next to each other.
- Large totals: 64 bits.
I've built my logic, show the code
Java
class Solution {
public long minWork(int[] a) {
long carry = 0, work = 0; // carry: wine that must cross the gap after this house
for (int i = 0; i < a.length - 1; i++) {
carry += a[i];
work += Math.abs(carry); // every bottle crossing a gap costs one unit
}
return work;
}
}C++
class Solution {
public:
long long minWork(vector<int>& a) {
long long carry = 0, work = 0; // carry: wine that must cross the gap after this house
for (size_t i = 0; i + 1 < a.size(); i++) {
carry += a[i];
work += llabs(carry); // every bottle crossing a gap costs one unit
}
return work;
}
};Python
class Solution:
def minWork(self, a: list[int]) -> int:
carry = work = 0 # carry: wine that must cross the gap after this house
for x in a[:-1]:
carry += x
work += abs(carry) # every bottle crossing a gap costs one unit
return workCommon mistakes
- Adding the last house's running total, which is always 0.
- Summing the values instead of the running totals.