Maximum Profit in a Stock Market

本文介绍了一种寻找股票买卖最佳时机以获得最大利润的算法。通过遍历每日股价记录并跟踪最低购买价格及最大利润,该算法能快速找出最优买卖日期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Source:http://programming4interviews.wordpress.com/category/dynamic-programming/


Given a week`s daily prices of a stock, find out the days in which we should buy and sell the stocks such that the profit is maximum.

This is a common interview question and also very special to me as this was asked to me in an interview I attended some time back. I could not crack it fully during the interview. Taken up multiple times to solve, but left it half way. Today I am happy that finally I could crack this problem and also write a working code for it. Interestingly the answer was always in front of me here . Its just that i did not pay much attention to it.

Go through the elements in the array, keep track of the maximum profit and minimum stock price seen till then, you have your answer.

public static int findMaxProfit(int[] stockPriceSamples) {
	int maxProfit = 0;
	int minTillNow = stockPriceSamples[0];
	for (int i = 0; i < stockPriceSamples.length; i++) {
		int profit = stockPriceSamples[i] - minTillNow;
		maxProfit = Math.max(profit, maxProfit);
		minTillNow = Math.min(stockPriceSamples[i], minTillNow);
	}
	return maxProfit;
}

The driver code

public static void main(String[] args) {
	int[] stockPrices = new int[] { 5, 2, 10, 3, 10, 5, 5, 1, 17, 4, 100 };
	System.out.println(findMaxProfit(stockPrices));
}

The answer is

99

Again this is not something which is newly invented. I could find at least 3-4 links where this problem is explained very well. I personally like the code talk for me :-) . For those who want to read more and to see some alternate solutions, I found this link to be very useful.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值