תיאור השאלה
You are given an array prices where prices[i] is the price of a stock on day i. Find the maximum profit you can achieve with at most two transactions. You must sell before you buy again.
איך פותרים?
מחזיקים ארבעה מצבים ומעדכנים אותם בכל יום: buy1 (אחרי קנייה ראשונה), sell1 (אחרי מכירה ראשונה), buy2 ו־sell2. כל מצב הוא המקסימום בין להישאר בו לבין לעבור אליו מהמצב הקודם. התשובה היא sell2. סיבוכיות: O(n) זמן, O(1) זיכרון.
פתרון קוד
JavaScript
Python
function maxProfit(prices) {
let buy1 = -Infinity;
let sell1 = 0;
let buy2 = -Infinity;
let sell2 = 0;
for (const price of prices) {
buy1 = Math.max(buy1, -price);
sell1 = Math.max(sell1, buy1 + price);
buy2 = Math.max(buy2, sell1 - price);
sell2 = Math.max(sell2, buy2 + price);
}
return sell2;
}
לעבור את ראיון העבודה הבא שלך בהצלחה
קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.