Skip to content

Instantly share code, notes, and snippets.

@ShvedAction
Created March 7, 2020 16:54
Show Gist options
  • Save ShvedAction/32b393acf1b546be374d605bd0a6577d to your computer and use it in GitHub Desktop.
Save ShvedAction/32b393acf1b546be374d605bd0a6577d to your computer and use it in GitHub Desktop.
algorithmic problem about vine prices
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
unordered_map<string, int> cacheMaxPrices;
int maxPrice(vector<int> &prices, int start, int end){
if (end == start){
return 0;
}
string cacheKey = to_string(start) + "," + to_string(end);
if (cacheMaxPrices.find(cacheKey) != cacheMaxPrices.end()){
return cacheMaxPrices[cacheKey];
}
int yearsPast = start + prices.size() - end + 1;
int valueStart = prices[start] * yearsPast + maxPrice(prices, start + 1, end);
int valueEnd = prices[end-1] * yearsPast + maxPrice(prices, start, end - 1);
int res = valueStart > valueEnd ? valueStart : valueEnd;
cacheMaxPrices[cacheKey] = res;
return res;
}
int main(){
int count;
cin>>count;
vector<int> prices;
for(int i = 0; i<count; i++){
int price;
cin>>price;
prices.push_back(price);
}
int result = maxPrice(prices, 0, prices.size());
cout<<result<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment