about | help | code help+videos | done | prefs |
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and or sell the stock. You can only hold at most one share of the stock at any time. However, you are allowed to buy it and then immediately sell it on the same day. Return the maximum profit you can achieve. For example, given prices = {7, 1, 5, 3, 6, 4}, the maximum profit is 7. You buy on day 2 (price = 1) and sell on day 3 (price = 5), for a profit of 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), for a profit of 3. Total profit is 4 + 3 = 7. If prices = {1, 2, 3, 4, 5}, then profit is 4 by buying on day 1 and selling on day 5. If prices = {7, 6, 4, 3, 1}, then no transaction is made and profit is 0. You must solve this in linear time. Requirements: You must solve this problem in Θ(n) amortized time. maxProfit([3, 3, 5, 0, 0, 3, 1, 4]) → 8 maxProfit([7, 1, 5, 3, 6, 4]) → 7 maxProfit([1, 2, 3, 4, 5]) → 4 ...Save, Compile, Run (ctrl-enter) |
Progress graphs:
Your progress graph for this problem
Random user progress graph for this problem
Random Epic Progress Graph
Difficulty: 210
Copyright Nick Parlante 2017 - privacy