最大子数组的和

这里就直接上代码了,非常简单的一个代码了,动态规划

#include 
#include 

// using namespace std;
int main() {
  int arr[] = {-1, 5, -4, 7, 3, -2, -1, 4, -6};
  int len = sizeof(arr)/sizeof(int);
  int sum_val = 0;
  int start_index = 0;
  int end_index = 0;
  int sum_tmp1 = 0;
  int sum_tmp2 = 0;
  for (int i = 0; i < len; i++) {
    if (arr[i] > sum_tmp1 + arr[i]) {
      sum_tmp1 = arr[i];
      start_index = i;
    } else {
      sum_tmp1 = sum_tmp1 + arr[i];
    }
    if (sum_tmp1 > sum_val) {
      sum_val = sum_tmp1;
      end_index = i;
    }
  }
  std::cout << "sum_val: " << sum_val << std::endl;
  std::cout << "start_index,end_index: " << start_index << "," << end_index << std::endl;
  return 0;
}

你可能感兴趣的:(基础学习-C++)