C++ a program to calculate the greatest profit -


this program accepts input of everyday prices of , calculates greatest profit. , list of prices end -1. example, if input 20,30,10,50,-1 , means @ first day $20,in second day $30,etc. greatest profit output $40 since buy on third day @ $10 , sell in fourth day @ $50.

this school assignment , teacher not allow me use array. program fine except in case e.g. if input 20 30 10, greatest profit $(30-10) how fix if not store number after maximum number e.g. 10 minimum number? or other codes fulfil purpose of program?

#include<iostream> using namespace std; int main() {     int c(0), r(0), n1(0), min(0), max(0), l(0), s(0);      cout << "please enter prices: ";      while (n1 != -1) {         cin >> n1;         if (min == 0 && n1>0)         {             min = n1;         }         c++;         if (n1 <= 0 && n1 != -1) { cout << "invalid. input again. please make sure it's positive number!" << endl; r++; }         else {             if (n1<min && n1 != -1) { min = n1; s++; }             if (n1 >= max && (c - r)>(s + 1)) { max = n1; l = c; }             cout << c << s + 1 << l << endl;         }     }     cout << max << min;     cout << endl << "largest amount earned: " << (max - min) << endl;     return 0; } 

you can calculate maximum profit using lowest price , not in future.

#include <iostream>  int main(void) {     int lowestprice = -1;     int highestprofit = 0;     int price, maxprofit;     while (std::cin >> price) {         if (price < 0) break;         if (lowestprice < 0 || price < lowestprice) lowestprice = price;         maxprofit = price - lowestprice;         if (maxprofit > highestprofit) highestprofit = maxprofit;     }     std::cout << highestprofit << std::endl;     return 0; } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -