题目描述1
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 maxProfile=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i]<prices[i+1]){
maxProfile+=prices[i+1]-prices[i];
}
}
return maxProfile;
}
}
题目描述2
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) {
int maxProfile=0;
for(int i=0;i<prices.length;i++){
for(int j=i+1;j<prices.length;j++){
maxProfile=maxProfile>(prices[j]-prices[i])?maxProfile:(prices[j]-prices[i]);
}
}
return maxProfile;
}
}
题目描述3(较为复杂些了)
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 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).
解析:最多买卖两次,可以以i为分界线,然后在i的左侧搜索最大的利润,在i的右侧也搜索最大的利润,最后算总的利润。
测试用例
输入:
[6,1,3,2,4,7]
输出:
7
import java.util.*;
public class Solution {
public int maxProfit(int[] prices) {
int maxProfile=0;
int length=prices.length;
for(int i=0;i<length;i++){
int leftMax=0,rightMax=0;
for(int j=0;j<i;j++){//搜索左侧的最大利润
for(int k=j+1;k<=i;k++){
int temp =prices[k]-prices[j];
leftMax=leftMax>temp?leftMax:temp;
}
}
for(int j=i+1;j<length;j++){//搜索右侧的最大利润
for(int k=j+1;k<length;k++){
int temp =prices[k]-prices[j];
rightMax=rightMax>temp?rightMax:temp;
}
}
if(leftMax+rightMax>maxProfile){
maxProfile=leftMax+rightMax;
}
}
return maxProfile;
}
}