NC22 合并两个有序的数组
给出一个整数数组A和有序的整数数组B,请将数组B合并到数组A中,变成一个有序的升序数组
注意:
1.可以假设A数组有足够的空间存放B数组的元素,A和B中初始的元素数目分别为M和N,的数组空间大小为M+N2.不要返回合并的数组,返回是空的,将数组B的数据合并到A里面就好了
3.数组在[0,m-1]的范围也是有序的
例1:
A: [1,2,3,0,0,0],m=3
B: [2,5,6],n=3
合并过后A为:
A: [1,2,2,3,5,6]
从大到小 从右到左
i=m-1; j=n-1;index=m+n-1
while i、j>=0 a[index--]=a[i]>b[j]?a[i--]:b[j--]
while j>=0 a[index--]=b[j--]
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int i = m-1, j = n-1, index = m+n-1;
while(i >= 0 && j >= 0){
A[index--] = A[i] > B[j] ? A[i--] : B[j--];
}
while(j >= 0){
A[index--] = B[j--];
}
}
}
NC7 买卖股票的最好时机
描述
假设你有一个数组,其中第 i 个元素是股票在第 i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。示例1
输入:
[1,4,2]复制返回值:
3复制
示例2
输入:
[2,4,1]复制返回值:
2
法一:
f(i,0) = max( f(i-1,0), f(i-1,1)+price[i] )
f(i,1) = max( f(i-1,1), f(i-1,0)-price[i])
∵只能买卖一次 ∴f(i-1,0) = 0 f(i,1) = max( f(i-1,1), -price[i])
法二:
profit - 记录最大利润
mmin - 记录股票最小值
遍历维护
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
// 0
int profit = -1;
int mmin = prices[0];
for(int p:prices){
if(mmin > p)
mmin = p;
if(profit < p-mmin)
profit = p-mmin;
}
return profit;
}
}