{ "cells": [ { "cell_type": "markdown", "source": [ "Say you have an array `prices` for which the _i_ th element is the price of a\n", "given stock on day _i_.\n", "\n", "Design an algorithm to find the maximum profit. You may complete as many\n", "transactions as you like (i.e., buy one and sell one share of the stock\n", "multiple times).\n", "\n", "**Note:** You may not engage in multiple transactions at the same time (i.e.,\n", "you must sell the stock before you buy again).\n", "\n", "**Example 1:**\n", "\n", "\n", "\n", " Input: [7,1,5,3,6,4]\n", " Output: 7\n", " Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\n", " Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\n", "\n", "\n", "**Example 2:**\n", "\n", "\n", "\n", " Input: [1,2,3,4,5]\n", " Output: 4\n", " Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n", " Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are\n", " engaging multiple transactions at the same time. You must sell before buying again.\n", "\n", "\n", "**Example 3:**\n", "\n", "\n", "\n", " Input: [7,6,4,3,1]\n", " Output: 0\n", " Explanation: In this case, no transaction is done, i.e. max profit = 0.\n", "\n", "\n", "\n", "**Constraints:**\n", "\n", " * `1 <= prices.length <= 3 * 10 ^ 4`\n", " * `0 <= prices[i] <= 10 ^ 4`" ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "max_profit (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "function max_profit(prices::Vector{Int})::Int\n", " res = 0\n", " for i in 2:length(prices)\n", " res += (prices[i] > prices[i - 1]) ? (prices[i] - prices[i - 1]) : 0\n", " end\n", " return res\n", "end\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }