תיאור השאלה
You are given an array prices where prices[i] is the price of a stock on day i. Choose a single day to buy and a later day to sell to maximize your profit. Return the maximum profit, or 0 if no profit is possible.
איך פותרים?
מעבר אחד על המערך: שומרים את המחיר הנמוך ביותר שראינו עד עכשיו, ובכל יום בודקים כמה היינו מרוויחים אם היינו מוכרים היום. התשובה היא הרווח הגבוה ביותר שראינו. סיבוכיות: O(n) זמן, O(1) זיכרון.
פתרון קוד
JavaScript
Python
function maxProfit(prices) {
let minPrice = Infinity;
let best = 0;
for (const price of prices) {
minPrice = Math.min(minPrice, price);
best = Math.max(best, price - minPrice);
}
return best;
}
לעבור את ראיון העבודה הבא שלך בהצלחה
קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.