| 1. |
Given an array whose elements denote the price of a stock on the ith day, find the maximum profit that you can make by purchasing and selling those stocks. No stock can be bought unless the previously bought stock has been sold. |
|
Answer» For example, Explanation of the above test case: In our approach, we will iterate through each of the prices of the STOCK starting from day 1 and check if its price is greater than the PREVIOUS day’s price. This is because there is no limit on the number of transactions being made. For example, buying a stock on day 1 and selling on day 4 is equivalent to buying a stock on day 1, selling on day 2, buying on day 2, selling on day 3, buying on day 3, selling on day 4. Code: #include<bits/stdc++.h>using namespace STD;//function to calculate the maximum profit attainableint maximiseProfit(int prices[], int size){ int maximumProfit = 0; // stores the maximum profit for(int i = 1; i < size; i ++) { if(prices[i] - prices[i - 1] > 0) maximumProfit += prices[i] - prices[i - 1]; } return maximiseProfit;}int main(){ int prices[] = { 100, 180, 260, 310, 40, 535, 695 }; int size = sizeof(prices) / sizeof(prices[0]); cout << maximiseProfit(prices, size) << endl; return 0;}Explanation: In the above code, the function maximiseProfit calculates the maximum profit attainable on the given SET of stock prices. We iterate over the array and add up any DIFFERENCE in which an element is greater than its preceding element. |
|