Say you have an array for which the i th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length < 1 || prices == null) return 0;
int minprice = prices[0];
int profit = 0;
for(int i = 1; i < prices.length; i++)
{
profit = Math.max(profit, prices[i]-minprice);
minprice = Math.min(minprice, prices[i]);
}
return profit;
}
}
Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
if(prices.length < 1 || prices == null) return 0;
for(int i = 1; i < prices.length; i++)
{
int differ = prices[i]-prices[i-1];
if(differ > 0) profit += differ;
}
return profit;
}
}