Solve in cpp
Created on: July 4, 2025
Created on: July 4, 2025
pythonfrom PIL import Image import matplotlib.pyplot as plt img = Image.open('/mnt/data/1751659636521526385411074233014.jpg') plt.imshow(img) plt.axis('off') (-0.5, 3999.5, 2999.5, -0.5)
pythonplt.figure(figsize=(6,10)) plt.imshow(img.crop((0,150,600,1100))) plt.axis('off') (-0.5, 599.5, 949.5, -0.5)
pythonplt.figure(figsize=(6,10)) plt.imshow(img.crop((0,400,600,1500))) plt.axis('off') (-0.5, 599.5, 1099.5, -0.5)
pythonplt.figure(figsize=(6,10)) plt.imshow(img.crop((0,1000,600,1900))) plt.axis('off') (-0.5, 599.5, 899.5, -0.5)
pythonplt.figure(figsize=(6,10)) plt.imshow(img.crop((0,1400,600,2500))) plt.axis('off') (-0.5, 599.5, 1099.5, -0.5)
Think of building the final array b
that must be non-decreasing and never smaller than the given power array a
.
texta[i] … original power inc[i] … how much we add to a[i] b[i] = a[i] + inc[i] … final value
An operation “add z to a contiguous sub-array” can be split into z unit-operations that each cost 1, so the total cost is
textcost = Σ inc[i] started for the *first* time = inc[0] + Σ max(0, inc[i] − inc[i-1])
Hence we only pay when the running “height” inc
climbs above its previous level.
To spend the least possible, at every position we push the current element up just enough to keep the whole prefix sorted, and nothing more.
textcur_inc = 0 // inc[i-1] prev_b = a[0] // b[i-1] ans = 0 for i = 0 … n-1 need_b = max(prev_b, a[i]) // smallest allowed b[i] inc_i = need_b - a[i] // how much we must add here if inc_i > cur_inc // we raise the “water level” ans += inc_i - cur_inc // pay only the extra height cur_inc = inc_i prev_b = need_b
ans
is the minimum possible sum of z-values.
All numbers fit in 64 bit (n ≤ 1e5
, power[i] ≤ 1e9
), so use long long
.
cpp#include <bits/stdc++.h> using namespace std; /* * Complete the 'findMinimumSum' function below. * The function is expected to return a LONG_INTEGER. * The function accepts INTEGER_ARRAY power as parameter. */ long long findMinimumSum(vector<int> power) { const int n = power.size(); long long ans = 0; // minimum sum of z's long long cur_inc = 0; // inc at position i-1 long long prev_b = power[0]; // b at position i-1 for (int i = 0; i < n; ++i) { long long need_b = max(prev_b, (long long)power[i]); long long inc_i = need_b - power[i]; if (inc_i > cur_inc) // pay only for extra raise ans += inc_i - cur_inc; cur_inc = inc_i; prev_b = need_b; } return ans; }
need_b
is the smallest value that keeps the prefix sorted.inc_i
is therefore the minimum increment at i
.inc_i
exceeds the previous increment counts each new “layer” exactly once, which is the optimal cost proven by the unit-operation view.The solution runs in linear time and constant extra memory, easily fitting the constraints.