日期:2025年5月20日
ZeroJudge 題目連結:l919. P.2 珠寶交易 (Jewel)
解題想法
這題理論上用貪心法就能解,有通過範例測資,但是無法送出解答。
Python 程式碼
無法送出解答。
import sys
for line in sys.stdin:
n = int(line) # n 天
buy = float('inf') # 最低買價,預設為正無窮大
profit = 0 # 最大利潤,預設為 0
best_buy_dat, best_sell_day = 0, 0 # 最佳買入、𧶠出時機
buy_day = 0 # 買入時機
for i, p in enumerate(map(int, input().split()), start=1): # 第 i 天,價格 p
if p < buy: # 如果當天的價格小於 buy,更新 buy 及 buy_day
buy = p; buy_day = i
elif p - buy > profit: # 價差大於 profit
profit = p - buy # 更新 profit
best_sell_day = i # 更新 sell_day
best_buy_day = buy_day # 更新 best_buy_day
if profit > 0: print(best_buy_day, best_sell_day)
else: print(-1)
C++ 程式碼
無法送出解答。
#include <cstdio>
int main () {
int n; // n 天
while(scanf("%d", &n) != EOF) {
int buy = 1E9; // 最低買價,預設為正無窮大
int profit = 0, best_buy_day = 0, best_sell_day = 0, buy_day = 0; // 最大利潤,最佳買入、𧶠出時機,買入時機
for(int i=1; i<=n; i++) { // 第 i 天
int p; scanf("%d", &p); // 價格 p
if (p < buy) { // 如果當天的價格小於 buy,更新 buy 及 buy_day
buy = p; buy_day = i;
} else if (p - buy > profit) { // 價差大於 profit
profit = p - buy; // 更新 profit
best_sell_day = i; // 更新 sell_day
best_buy_day = buy_day; // 更新 best_buy_day
}
}
if (profit > 0) printf("%d %d\n", best_buy_day, best_sell_day);
else printf("-1\n");
}
return 0;
}
沒有留言:
張貼留言