您的位置:首页 > 其它

Leetcode---Best Time to Buy and Sell Stock I & II

2018-03-14 16:53 411 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode