Answer to Question #325481 in C++ for Anji

Question #325481

you want tobuy a particular stock at its loerest price andsell it later at its highest price,since the stock market is unpredictable,yousteal the price plans of a company for this stockfor the next N days.

Find the best price you can get to buy this stock to achieve maximum profit.

Note:The initial price of the stock is 0.

Input1:Nnumber of days.

Input2:Array representing changein stock price for the day.

Output: Your function must return the best price to buy the stock at.

Example:

Input1:5

Input2:{-39957,-17136,35466,21820,-26711}

Output:-57093


1
Expert's answer
2022-04-12T13:28:16-0400
#include <iostream>
#include <vector>


int main() {
  int n;
  std::cout << "Enter the number of days: ";
  std::cin >> n;
  std::vector<int> changes(n);
  std::cout << "Enter price changes separated with a space: ";
  for (int i = 0; i < n; ++i) {
    std::cin >> changes[i];
  }


  std::vector<int> prices(n + 1);
  prices[0] = 0;
  for (int i = 0; i < n; ++i) {
    prices[i + 1] = prices[i] + changes[i];
  }
  
  int bestPrice = 0;
  int difference = 0;
  for (int i = 0; i < n; ++i) {
    for (int j = i + 1; j <= n; ++j) {
      int d = prices[j] - prices[i];
      if (d > difference) {
        bestPrice = prices[i];
        difference = d;
      }
    }
  }
  std::cout << "Best price: " << bestPrice << '\n';
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS