πŸ‘Š PS/Algorithm

[Baekjoon] 11501번: 주식

hades1 2024. 8. 7. 16:07

πŸ₯… 문제

https://www.acmicpc.net/problem/11501

 

πŸ” 섀계

μ–΄λŠ λ‚ μ˜ 가격보닀 μ΄ν›„μ˜ λ‚  가격듀 쀑 κ°€μž₯ 높을 λ•Œ νŒ”μ•„μ•Ό 이읡을 μ΅œλŒ€ν™”ν•  수 μžˆλ‹€. κ°€μž₯ 가격이 높은 날에 νŒ”κ³ , κ·Έ λ‚  μ΄ν›„μ˜ λ‚ λ“€ μ€‘μ—μ„œ κ°€μž₯ 가격이 높은 λ‚  νŒ”κ³ , 이 방식을 λ°˜λ³΅ν•΄μ•Ό ν•œλ‹€.

 

ν˜„μž¬ μƒν™©μ—μ„œ κ°€μž₯ 높은 가격을 κ΅¬ν•˜κΈ° μœ„ν•΄ μš°μ„ μˆœμœ„ 큐λ₯Ό ν™œμš©ν–ˆλŠ”λ°, μ€‘μš”ν•œ 것은 λ‚¨μ•„μžˆλŠ” 가격듀 쀑 κ°€μž₯ 높은 가격에 차읡을 보고 νŒλ§€ν•œ 주식 가격듀이 μžˆμœΌλ―€λ‘œ, 인덱슀λ₯Ό ν•¨κ»˜ λ‹΄μ•„ μ œκ±°ν•΄μ•Ό ν•œλ‹€.


 

맨 λ’€κΉŒμ§€ κ³ λ €ν–ˆμ„ λ•Œ, 주식 가격이 κ°€μž₯ 높은 μ§€μ μ—μ„œ νŒ”μ•„μ•Ό ν•œλ‹€. μˆœμ„œλ₯Ό λ°”κΏ”μ„œ 맨 λ’€λΆ€ν„° μ΅œλŒ“κ°’μ„ κ°±μ‹ ν•˜λ©΄μ„œ 차이λ₯Ό λΉΌμ£Όλ©΄ κ°„λ‹¨ν•˜κ²Œ ν•΄κ²°ν•  수 μžˆλ‹€.

 

πŸ‘Š 풀이

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

int t, n;
vector<int> prices(1000000);

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> t;
	for (int i = 0; i < t; i++) {
		cin >> n;
		priority_queue<pair<int, int>> pq;
		long long result = 0;
		for (int j = 0; j < n; j++) {
			cin >> prices[j];
			pq.push({ prices[j], j });
		}

		int max_value;
		for (int j = 0; j < n; j++) {
			while (pq.top().second < j) {
				pq.pop();
			}
			max_value = pq.top().first;
			if (max_value > prices[j]) {
				result += (max_value - prices[j]);
			}
		}
		cout << result << "\n";
	}

	return 0;
}

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

int t, n;
vector<int> stock(1000000);

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> t;

	for (int u = 1; u <= t; u++) {
		long long result = 0;
		cin >> n;
		for (int i = 0; i < n; i++) {
			cin >> stock[i];
		}

		int max_value = stock[n - 1];
		for (int i = n - 2; i >= 0; i--) {
			max_value = max(max_value, stock[i]);
			result += max_value - stock[i];
		}

		cout << result << "\n";
	}
	return 0;
}