Best Time to Buy and Sell Stock (Java)
2015-01-17 17:19
183 查看
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.
注意,买入的日期一定是早于卖出的日期,所以遍历数组时,维护一个max代表收益,min记录当前最小值。
Source
public class Solution {
public int maxProfit(int[] prices) {
int max = 0, min = Integer.MAX_VALUE;
for(int i = 0; i < prices.length; i++){
min = Math.min(min, prices[i]);
max = Math.max(max, prices[i] - min);
}
return max;
}
}
Test
public static void main(String[] args){
int[] prices = {4,1,2,3};
int a = new Solution().maxProfit(prices);
System.out.println(a);
}
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.
注意,买入的日期一定是早于卖出的日期,所以遍历数组时,维护一个max代表收益,min记录当前最小值。
Source
public class Solution {
public int maxProfit(int[] prices) {
int max = 0, min = Integer.MAX_VALUE;
for(int i = 0; i < prices.length; i++){
min = Math.min(min, prices[i]);
max = Math.max(max, prices[i] - min);
}
return max;
}
}
Test
public static void main(String[] args){
int[] prices = {4,1,2,3};
int a = new Solution().maxProfit(prices);
System.out.println(a);
}
相关文章推荐
- Best Time to Buy and Sell Stock III leetcode java
- 【Leetcode】Best Time to Buy and Sell Stock II in JAVA
- LeetCode(122) Best Time to Buy and Sell Stock II (Java)
- Java for LeetCode 123 Best Time to Buy and Sell Stock III【HARD】
- leetcode JAVA Best Time to Buy and Sell Stock II 3.43 难度系数3
- Best Time to Buy and Sell Stock Java
- Best Time to Buy and Sell Stock IV Leetcode Java
- Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】
- Java for LeetCode 121 Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock(JAVA)--动态规划
- [Leetcode] Best Time to Buy and Sell Stock II (Java)
- [Leetcode] Best Time to Buy and Sell Stock (Java)
- Best Time to Buy and Sell Stock II (Java)
- Best Time to Buy and Sell Stock III(JAVA)-动态规划
- Best Time to Buy and Sell Stock leetcode java
- leetcode java Best Time to Buy and Sell Stock
- [Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III
- Best Time to Buy and Sell Stock II Java
- [LeetCOde][Java] Best Time to Buy and Sell Stock III
- Java for LeetCode 122 Best Time to Buy and Sell Stock II