您的位置:首页 > 其它

LeetCode.121(122/123) Best Time to Buy and Sell Stock && II && III

2017-10-17 15:35 375 查看
题目121:

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)


Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

分析:

class Solution {
public int maxProfit(int[] prices) {
//给一个数组prices[],prices[i]代表股票在第i天的售价,求出只做一次交易(一次买入和卖出)能得到的最大收益
//低价买,高价卖
//思路:类似求解最长子串之和最优解,求出当前最小买入价,之后比较差价
//注意:跳过相同的数据
if(prices.length==0||prices==null)return 0;

//假设当前最小买入价
int min=prices[0];
int sum=0;
for(int i=0;i<prices.length;i++){
int compare=prices[i]-min;
if(compare==0){
continue;
}else if(compare<0){
//更小的买入价
min=prices[i];
}else{
sum=Math.max(compare,sum);
}
}

return sum;
}
}


题目122:

Say you have an array for which the ith 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).
分析:

class Solution {
public int maxProfit(int[] prices) {
//给一个数组prices[],prices[i]代表股票在第i天的售价,可以进行多次交易能得到的最大收益(前提:你卖之前必须买)
//低价买,高价卖
//思路:类似求解最长子串之和最优解,但是该题需要重新定位下标(即确保收益大于0)
if(prices.length==0||prices==null)return 0;

int sum=0;

for(int i=0;i<prices.length-1;i++){
int compare=prices[i+1]-prices[i];
if(compare>0){
sum+=compare;
}
}
return sum;
}
}


题目123:

Say you have an array for which the ith element is the price of a given stock on
day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

分析:

class Solution {
public int maxProfit(int[] prices) {
//求交易二次最大的收益
int sell1=0,sell2=0;
int buy1=Integer.MIN_VALUE,buy2=Integer.MIN_VALUE;
for(int i=0;i<prices.length;i++){
buy1=Math.max(buy1,-prices[i]);
sell1=Math.max(sell1,buy1+prices[i]);
buy2=Math.max(buy2,sell1-prices[i]);
sell2=Math.max(sell2,buy2+prices[i]);
}
return sell2;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐