תיאור השאלה
You are given an array prices where prices[i] is the price of a stock on day i. Each day you may buy and/or sell, holding at most one share at a time. Return the maximum profit you can achieve.
איך פותרים?
גרידי: כל עלייה בין יום ליום היא רווח שאפשר לקחת. סוכמים את כל ההפרשים החיוביים בין ימים עוקבים, וזה בדיוק הרווח של קנייה בכל שפל ומכירה בכל שיא. סיבוכיות: O(n).
פתרון קוד
JavaScript
Python
function maxProfit(prices) {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
}
return profit;
}
לעבור את ראיון העבודה הבא שלך בהצלחה
קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.