Equal Beauty CodeChef SnackDown 2021 Round 1A Question The beauty of an (non-empty) array of integers is defined as the difference between its largest and smallest element. For example, the beauty of the array [2,3,4,4,6] is 6−2=4. An array A is said to be good if it is possible to partition the elements of A into two non-empty arrays B1 and B2 such that B1 and B2 have the same beauty. Each element of array A should be in exactly one array: either in B1 or in B2. For example, the array [6,2,4,4,4] is good because its elements can be partitioned into two arrays B1=[6,4,4] and B2=[2,4], where both B1 and B2 have the same beauty (6−4=4−2=2). You are given an array A of length N. In one move you can: Select an index i (1≤i≤N) and either increase Ai by 1 or decrease Ai by 1. Find the minimum number of moves required to make the array A good. Input Format The first line of input contains a single integer T, denoting the number of test cases. The description of T test cases follow. Each test
Best Time to Buy and Sell Stock III LeetCode Solution
Question
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
Example 4:
Input: prices = [1] Output: 0
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 105
Explanation
This problem is categorized as hard on LeetCode. This problem can be solved in few ways but doing so is quite difficult and more difficult is thinking the logic that is needed to be used. Here we are using Dynamic Programming and recursion to solve the problem. Before we start solving the problem we need to observe few key points which will be beneficial to solve this problem
- You can make at most 2 transactions.
- You should make maximum profit.
- You should not engage in multiple transactions simultaneously that is you have to sell a stock before re-buying some stock again.
Let us assume T[i][j] is maximum profit in i-th transaction in j-th day.
Thus T[i][j] can be written as
T[i][j] = max(T[i][j-1] , prices[j] - prices[k] + T[i-1][k]) where k = 0,..,j-1. Here T[i][j-1] means you are not doing any transaction on the j-th day so you have whatever profit you earned previous day.
(prices[j] - prices[k] + T[i-1][k]) this means if I am buying at day k then the profit is (prices[j] - prices[k]) and what we need to add is the profit in previous transaction on the k-th day. But this logic may give TLE so we optimize it further. If you look at the k-th loop we are trying to find k-th day to buy which is less than the j-th day. So (T[i-1][k] - prices[k]) should be maximum so that k will be selected. If we can keep the maximum in a variable we can avoid a loop. That's it now code it, hope you understood the explanation. I recommend try this first by yourself and then if you are stuck you can visit the solution given in Java, C++, Python.
If you are searching for similar problems like this then you can visit this link given below.
Program Code
Java
// Time Complexity: O(n)
// Space Complexity: O(n)
class Solution {
public int maxProfit(int[] prices) {
int N = prices.length;
int T[][] = new int[3][N];
for(int i = 1; i <= 2; i++) {
int maxDiff = T[i-1][0] - prices[0];
for(int j = 1; j < N; j++) {
T[i][j] = Math.max(T[i][j-1], prices[j] + maxDiff);
maxDiff = Math.max(maxDiff, T[i-1][j] - prices[j]);
}
}
return T[2][N-1];
}
}
C++
class Solution {
public:
int maxProfit(vector<int>& nums) {
int n = nums.size();
if(n==1) return 0;
vector<int> pre(n,0);
vector<int> post(n,0);
int mn = nums[0];
pre[0] = INT_MIN;
for(int i = 1;i<n;i++)
{
int temp = nums[i] - mn;
mn = min(mn,nums[i]);
pre[i] = max(pre[i-1],temp);
}
int mx = nums[n-1];
post[n-1] = INT_MIN;
for(int i = n-2;i>=0;i--)
{
int temp = mx - nums[i];
mx = max(mx,nums[i]);
post[i] = max(post[i+1],temp);
}
int ans = 0;
for(int i = 1;i<=n-3;i++)
{
ans = max(ans,pre[i]+post[i+1]);
}
ans = max(ans,pre[n-1]);
return ans;
}
};
Python
def maxProfit(self, prices):
dp = [[0,0] for i in range(len(prices))]
minPrice = prices[0]
curr_max1 = 0
curr_max2 = 0
temp = dp[0][0]-prices[0]
for i in range(len(prices)):
dp[i][0] = max(prices[i]-minPrice, curr_max1)
dp[i][1] = max(prices[i]+temp, curr_max2)
temp = max(temp, dp[i][0]-prices[i])
curr_max1 = max(curr_max1, dp[i][0])
curr_max2 = max(curr_max2, dp[i][1])
minPrice = min(minPrice, prices[i])
return max(dp[-1])
Links
More Information About LeetCode Daily Challenge
LeetCode is a great coding platform which provides daily problems to solve and maintain a streak of coding. This platform helps in improvement of coding skills and attempting the daily challenge makes our practice of coding regular. With its bunch of questions available it is one of the best coding platforms where you can have self improvement. LeetCode also holds weekly and biweekly contests which is a great place to implement you knowledge and coding skills which you learnt through out the week by performing the daily challenge. It also provides badges if a coder solves all the daily problems of a month. For some lucky winners T-shirts are also given and that too for free. If you get the pro version you can get more from LeetCode like questions that are asked in interviews, detailed explanation of each chapter and each concept and much more. LeetCode challenges participants with a problem from our carefully curated collection of interview problems every 24 hours.
All users with all levels of coding background are welcome to join!
@PREMIUM USERS will have an extra carefully curated premium challenge weekly and earn extra LeetCoin rewards. The premium challenge will be available together with the first October challenge of the week and closed together with the November challenge of the week.
Starting from 2021, users who completed all Daily LeetCoding Challenge non-premium problems for the month (with or without using Time Travel Tickets) will win a badge to recognize their consistency! Your badges will be displayed on your profile page. Completing each non-premium daily challenge. (+10 LeetCoins)
Completing 25 to 30 non-premium daily challenges without using Time Travel Ticket will be eligible for an additional 25 LeetCoins. (Total = 275 to 325 LeetCoins)
Completing all 31 non-premium daily challenges without using Time Travel Ticket will be eligible for an additional 50 LeetCoins, plus a chance to win a secret prize ( Total = 385 LeetCoins + *Lucky Draw)!
Lucky Draw: Those who complete all 31 non-premium daily challenges will be automatically entered into a Lucky Draw, where LeetCode staff will randomly select 3 lucky participants to each receive one LeetCode Polo Shirt on top of their rewards! Do you have experience trying to keep a streak but failed because you missed one of the challenges?
Hoping you can travel back to the missed deadline to complete the challenge but that's not possible......or is it?
With the new Time Travel Ticket , it's possible! In order to time travel, you will need to redeem a Time Travel Ticket with your LeetCoins. You can redeem up to 3 tickets per month and the tickets are only usable through the end of the month in which they are redeemed but you can use the tickets to make up any invalid or late submission of the current year. To join, just start solving the daily problem on the calendar of the problem page. You can also find the daily problem listed on the top of the problem page. No registration is required. The daily problem will be updated on every 12 a.m. Coordinated Universal Time (UTC) and you will have 24 hours to solve that challenge. Thar's all you needed to know about Daily LeetCode Challenge.
Comments
Post a Comment