Question
I'm looking for an algorithm that can efficiently compute the largest allowable contiguous subarray where the function PowerUsed(subarray) is less than the parameter AllowedEnergy. Each element in the array contains two values, startingEnergyUsed and ContinuousEnergyUsed, and PowerUsed is computed given two arrays of the same size denoting the startingEnergy and continuousEnergy values associated with each element (example below). The solution needs to be better than O(n^2) time complexity, and ideally would be O(n) space complexity or less.
Given:
- std::vector startingEnergyUsed
- std::vector continuousEnergyUsed
- long AllowedEnergy
Constraints:
- startingEnergyUsed.size() == continuousEnergyUsed.size()
- 1 <= startingEnergyUsed.size() <= 2^32 - 1
- 0 <= startingEnergyUsed[i] <= 2^32 - 1
- 0 <= continuousEnergyUsed[i] <= 2^32 - 1
- PowerUsed(x) <= LONG_MAX for any subvector x
- 0 < AllowedEnergy <= LONG_MAX
long PowerUsed(std::vector<int> & StartingEnergyUsed, std::vector<int> & ContinuousEnergyUsed)
{
long powerUsed = std::max_element(StartingEnergyUsed.begin(), StartingEnergyUsed.end());
long totalContinuousEnergy = std::accumulate(ContinuousEnergyUsed.begin(),ContinuousEnergyUsed.end());
powerUsed += totalContinuousEnergy * ContinuousEnergyUsed.size();
return powerUsed;
}
Additional details:
For reference, my current solution is the standard naïve O(n^2) solution involving iterating over each element and adding elements to it until the combined subvector exceeds AllowedEnergy and then trying again from the next element. I have minor improvements involving ignoring subarrays lower than my current max, but nothing that improves the big O time complexity.
The information I've provided is in C++ as that is what I've been using to work on the problem, but since this is an algorithm question I'm open to any solution based in procedural or object oriented languages.