StockHistory

Cute_Security15·2025년 11월 25일

알고리즘

목록 보기
20/30

문제

초기 투자금, 매월 투자금, 주식 히스토리가 주어지고

매월 초에 주식을 구매하고, 중간에 주식을 팔지 않는다고 한다

이때, 다음 달에 더 좋은 수익률이 있으면 주식을 구매하지 않아도 된다

기간의 끝에 얻을 수 있는 최대 이익을 리턴한다

예시 입력

1)
1000, 
0, 
{
    "10 20 30", 
    "15 24 32"
}

2)
1000,
0,
{
    "10", 
    "9"
}

3)
100,
20,
{
    "40 50 60",
    "37 48 55",
    "100 48 50",
    "105 48 47",
    "110 50 52",
    "110 50 52",
    "110 51 54",
    "109 49 53"
}

예시 출력

500
0
239

생각의 변화

100 투자시
10짜리가 15로 되면 가치는 1000에서 1500으로, 차익은 1500-1000 = 500

식으로 표현하면

100 투자시
40짜리가 109 가 되면 이익은

100x(109/40) - 100

20 투자시
구매하지 않은 경우 이익은

20x1 - 20

다음에 더 좋은 투자기회가 있으면 이번에 투자하지 않아도 된다

매 회차 최적 비율 획득

금액은 무시 no tracking
리스트대로 수행
현재 금액 전체 투자

pseudo code

maximumEarning(initialInvestment, monthlyContribution, stockPrices)
    vector<int> finalPrice
    
    stringstream ss(stockPrices.back())
    
    int price
    while (ss >> price)
        finalPrice.push_back(price)
        
    int n = stockPrices.size() - 1
    
    vector<double> maxrates(n, 0)
    
    int k = 1
    
    for (auto s = stockPrices.rbegin() + 1; s != stockPrices.rend(); s++)
        double maxrate = 1
        
        stringstream ss(*s)
        
        int price
        int i = 0
        
        while (ss >> price)
            double r = (double)finalPrice[i] / price
            maxrate = max(maxrate, r)
            i++
            
        maxrate[n-k] = maxrate
        k++
        
    int fund = initialInvestment
    double profit = 0
    
    for (int i = 0; i < n; i++)
        if (i+1 < n  &&  maxrates[i] < maxrates[i+1])
        
        else if (maxrates[i] >= 1)
            profit += (double)fund * maxrates[i] - fund
            fund = 0
            
        fund += monthlyContribution
        
    return profit
profile
관심분야 : Filesystem, Data structure, user/kernel IPC

0개의 댓글