Problem
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.
Analysis
- 遍历数组,记录当前最小值,记录当前最大profit
- 当前profit = 当前值 - 当前最小值
- 时间复杂度: O(n)
- 空间复杂度: O(1)
Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 2015/12/28 | |
// Highlight: keep track of min value | |
public class Solution { | |
public int maxProfit(int[] prices) { | |
if(prices==null || prices.length==0) return 0; | |
int rnt = 0; | |
int min = prices[0]; | |
for(int i=1; i<prices.length; i++){ | |
//update min value before or at the i-th days | |
min = Math.min(prices[i],min); | |
//calculate the profit | |
rnt = Math.max(rnt, prices[i]-min); | |
} | |
return rnt; | |
} | |
} |
[1] https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
No comments:
Post a Comment