int maxProfit(vector<int>& prices) { if (prices.size() == 0) return 0; vector<int> profits(prices.size(), 0); int minPrice = INT_MAX; int maxProfit = 0; for (int i = 0; i < prices.size(); ++i) { if (minPrice > prices[i]) minPrice = prices[i]; profits[i] = prices[i] - minPrice; maxProfit = max(maxProfit, profits[i]); } return maxProfit; }
// DP: int maxProfit(std::vector<int>& prices) { if (prices.size() <= 1) return 0; std::vector<int> profits(prices.size(), 0); for (int i = 1, iEnd = (int)prices.size(), lowestPrice = prices[0]; i < iEnd; ++i) { if (prices[i] < lowestPrice) lowestPrice = prices[i]; profits[i] = std::max(profits[i-1], prices[i] - lowestPrice); } int maxProfit = profits.back(); for (int i = (int)prices.size()-1, highestPrice = 0; i > 0; --i) { highestPrice = std::max(prices[i], highestPrice); maxProfit = std::max(maxProfit, (highestPrice - prices[i])+profits[i-1]); } return maxProfit; }
int maxProfit(std::vector<int> &prices) { int len = prices.size(); if (len < 2) return (0); std::vector<int> profits(len, 0); int lowest = prices.front(); for (int i = 0; i < len; ++i) { profits[i] = std::max(profits[i], prices[i] - lowest); lowest = std::min(lowest, prices[i]); } int profit = 0; int highest = prices.back(); int sum = 0; for (int i = len - 1; !(i < 0); --i) { profit = std::max(profit, highest - prices[i]); highest = std::max(highest, prices[i]); sum = std::max(sum, profit + profits[i]); } return (sum); }
int main ( void ) { FILE *fcost,*fp_extra,*fp_entries; int ask,cost_exists; char i='0',ar_ext[8], ch='&',entries[13]="Entries.txt",cost[9]="Cost.txt",extra[10]="Extra.txt"; fcost=fopen(cost,"r"); if(fcost==NULL) { printf("Couldn't find %s\nThe file will now be created. Please insert the different cost values, before advancing to menu.\n",cost); edit_cost(cost,1); } else { printf("Cost file detected. Advancing to menu.\n",cost); fclose(fcost); } while(ch!='8') { printf("\n1. New entry\n2. Calculate cost\n3. Print entry status\n4. Print non delivered entries\n5. Profits\n6. Services cost\n7. Update services cost\n8. Quit\n Your input:"); ch=getchar(); printf("\n** Your input was: %c ** \n",ch); switch (ch) { case '1': { ask=0; add_entry(entries,extra,cost,ask); }break;//don't ask. case '2': { ask=1; add_entry(entries,extra,cost,ask); //fflushnew(&ch); }break;//ask. case '3': {fflushnew(&ch);search_entry(entries); } break; case '4': {incomplete(entries); } break; case '5': {profits(entries);} break; case '6': {edit_cost(cost,0);} break;//view cost file case '7': {edit_cost(cost,1);fflushnew(&ch);} break;//edit cost file case '8': break;//quit default: printf("Please enter correct input (1-8)"); } if(ch!='8')fflushnew(&ch); } system ("pause"); return 0; }