top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Find Buy/Sell Prices in Array of Stock Values to Maximize Profit

0 votes
397 views

Problem: You have given a stock prices for next 10 days. Find out: max benefit in best time complexity in buy and sell 1 share ?
Condition: Share must be sold any day after buying date.

For ex:
Share price in thousands
5 1 4 6 7 8 4 3 7 9
Max benefit 9 – 1 = 8 thousand

posted Aug 19, 2016 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Solution:

The max benefit is the case where you buy at the lowest price and sell at the highest, with the condition that the buy has to be before sell.

public static int getMaxBenefit(int []S)
{
 int maxBenefit = 0;
 int minPrice = Integer.MAX_VALUE;
 for (int i = 0; i < S.length; i++)
 {
 maxBenefit = Math.max(maxBenefit, S[i] - minPrice);
 minPrice = Math.min(S[i], minPrice);
 }

 return maxBenefit;
}

Time Complexity: O(N)

answer Sep 22, 2016 by Manikandan J
Similar Questions
+1 vote

Given 3 sorted array of size x, y, z. what is the minimum time taken to find the kth smallest element in the merged sorted array.

+5 votes

Given an unsorted array, find the max length of subsequence in which the numbers are in incremental order.

For example: If the input array is {7, 2, 3, 1, 5, 8, 9, 6}, a subsequence with the most numbers in incremental order is {2, 3, 5, 8, 9} and the expected output is 5.

+5 votes

Given an array A of unsigned 32-bit ints, choose two in-bounds indices i, j so as to maximize the value of A[i] ^ A[j], where ^ is the bitwise XOR (exclusive OR) operator. If there are multiple possible answers, print any one.

Example Input:

4 2 0 13 49 

Output:

3 4 

Explanation: 13 ^ 49 is 60, 13 and 49 are positioned at indexes 3 and 4. Printing "4 3" would have been equally valid.
EDIT:- Let k be the bit width (maximum number of bits) of the primitive.
Constraint:- Only Sub-quadratic complexity. An O(k*arr.length) time.

+1 vote

Find the count k by which array has been rotated in the rotated sorted array. So for example we have sorted array as 2,3,6,12, 15, 18. Now suppose the array is rotated k times ( we don’t know k), such that array becomes 15, 18,2,3,6,12 We have to find K?

...