Pages

Wednesday, April 9, 2025

Buy and Sell Stocks (Code) in C++

 #include<iostream>

#include <climits>

using namespace std;


void maxProfit(int *prices, int n) {

    // finds best buy
    int bestBuy[100000]; // 10^5
    bestBuy[0] = INT_MAX;

    for(int i=1; i < n; i++) {
        bestBuy[i] = min(bestBuy[i-1], prices[i-1]);
    }

    // finds best profit
    int maxProfit = 0;
    for(int i=0; i<n; i++) {
        int currProfit = prices[i] - bestBuy;
        maxProfit = max(maxProfit, currProfit);
    }
   
    // O(n + n) = O(2n) = O(n)
    cout << "max profit = "  << maxProfit << endl;

    cout << endl;

}

int main(){
    int prices[6] = {7, 6, 5, 4, 3, 2};
    int n = sizeof(prices) / sizeof(int);

    maxProfit(prices, n);

    return 0;
}


No comments:

Post a Comment

Multi-dimensional ArrayList in Java

  // import java.util.ArrayList; import java.util. * ; // import java.util.Collections; public class Classroom {     public static voi...