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
#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;
}
Comments
Leave a comment