Say you have an array for which the ith 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.
My Solution
代码的run time是3ms (15.48%),时间复杂度是,空间复杂度是。
public class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if (len <= 1) {
return 0;
}
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < len; ++i) {
maxProfit = (maxProfit > (prices[i] - minPrice)) ? maxProfit : (prices[i] - minPrice);
minPrice = (minPrice < prices[i]) ? minPrice : prices[i];
}
return maxProfit;
}
}
Description
Say you have an array for which the ith 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.
My Solution
代码的run time是3ms (15.48%),时间复杂度是,空间复杂度是。
Analysis
水题,没什么好说的。